1 <?php
2
3 namespace Docolight\Http;
4
5 use Docolight\Support\Fluent;
6 use Docolight\Http\Contracts\Arrayable;
7
8 /**
9 * This is a simple abstraction over top an HTTP response. This
10 * provides methods to set the HTTP status, the HTTP headers,
11 * and the HTTP body. Please use this response only if you want
12 * to send a [JSON](http://json.org) response.
13 *
14 * ```php
15 * $response = new Docolight\Http\JsonResponse(new Docolight\Http\Headers());
16 *
17 * // Or you can resolve via factory
18 * // $response = with(new Docolight\Http\ResponseFactory())->produce('json');
19 *
20 * // Move even shorter way
21 * // $response = container('response')->produce('json');
22 *
23 * // Set your header
24 * $response->headers->set('Foo', 'Bar');
25 *
26 * // Set your response status
27 * $response->setStatus(202);
28 *
29 * // Set your response body
30 * $response->setBody(new Docolight\Support\Fluent(array('my_json_index' => 'my_json_value')));
31 *
32 * // Send your response to client
33 * $response->send();
34 *
35 * // In shorter way
36 * // response(
37 * // 'json',
38 * // 200,
39 * // new Docolight\Support\Fluent(array('my_json_index' => 'my_json_value')),
40 * // array('Foo' => 'Bar')
41 * // )->send();
42 * ```
43 *
44 * @author Krisan Alfa Timur <krisanalfa@docotel.co.id>
45 */
46 class JsonResponse extends MimeResponse
47 {
48 /**
49 * {@inheritdoc}
50 */
51 public function init()
52 {
53 parent::init();
54
55 if ($this->body === null) {
56 $this->body = $this->getEmpty();
57 }
58 }
59
60 /**
61 * {@inheritdoc}
62 */
63 protected function getContentType()
64 {
65 return 'application/json';
66 }
67
68 /**
69 * {@inheritdoc}
70 */
71 protected function convertToStringRepresentation(Arrayable $body)
72 {
73 return json_encode($body->castToArray());
74 }
75
76 /**
77 * {@inheritdoc}
78 */
79 protected function getEmpty()
80 {
81 return new Fluent();
82 }
83 }
84