1 | <?php |
||
20 | abstract class ResponseBuilder implements Arrayable, Jsonable, JsonSerializable |
||
21 | { |
||
22 | /** |
||
23 | * Flag indicating if status code should be added to the serialized data. |
||
24 | * |
||
25 | * @var bool |
||
26 | */ |
||
27 | protected $includeStatusCode; |
||
28 | |||
29 | /** |
||
30 | * The HTTP status code for the response. |
||
31 | * |
||
32 | * @var int |
||
33 | */ |
||
34 | protected $statusCode; |
||
35 | |||
36 | /** |
||
37 | * Response factory used to generate JSON responses. |
||
38 | * |
||
39 | * @var \Illuminate\Contracts\Routing\ResponseFactory |
||
40 | */ |
||
41 | protected $responseFactory; |
||
42 | |||
43 | /** |
||
44 | * Constructor. |
||
45 | * |
||
46 | * @param \Illuminate\Contracts\Routing\ResponseFactory $responseFactory |
||
47 | */ |
||
48 | public function __construct(ResponseFactory $responseFactory) |
||
52 | |||
53 | /** |
||
54 | * Serialize the data and wrap it in a JSON response object. |
||
55 | * |
||
56 | * @param int|null $statusCode |
||
57 | * @param array $headers |
||
58 | * @return \Illuminate\Http\JsonResponse |
||
59 | */ |
||
60 | public function respond(int $statusCode = null, array $headers = []):JsonResponse |
||
70 | |||
71 | /** |
||
72 | * Set the HTTP status code for the response. |
||
73 | * |
||
74 | * @param int $statusCode |
||
75 | * @return self |
||
76 | */ |
||
77 | public function setStatus(int $statusCode):ResponseBuilder |
||
83 | |||
84 | /** |
||
85 | * Set a flag indicating if status code should be added to the response. |
||
86 | * |
||
87 | * @param bool $includeStatusCode |
||
88 | * @return self |
||
89 | */ |
||
90 | public function setIncludeStatusCode(bool $includeStatusCode):ResponseBuilder |
||
96 | |||
97 | /** |
||
98 | * Convert the response to an Illuminate collection. |
||
99 | * |
||
100 | * @return \Illuminate\Support\Collection |
||
101 | */ |
||
102 | public function toCollection():Collection |
||
106 | |||
107 | /** |
||
108 | * Convert the response to JSON. |
||
109 | * |
||
110 | * @param int $options |
||
111 | * @return string |
||
112 | */ |
||
113 | public function toJson($options = 0) |
||
117 | |||
118 | /** |
||
119 | * Convert the object into something JSON serializable. |
||
120 | * |
||
121 | * @return array |
||
122 | */ |
||
123 | public function jsonSerialize() |
||
127 | |||
128 | /** |
||
129 | * Convert the response to an array. |
||
130 | * |
||
131 | * @return array |
||
132 | */ |
||
133 | abstract public function toArray():array; |
||
134 | |||
135 | /** |
||
136 | * Include a status code to the serialized data if enabled. |
||
137 | * |
||
138 | * @param array $data |
||
139 | * @return array |
||
140 | */ |
||
141 | protected function includeStatusCode(array $data):array |
||
149 | } |
Let’s take a look at an example: