-
Notifications
You must be signed in to change notification settings - Fork 29
/
JsonResponseTrait.php
421 lines (374 loc) · 12.2 KB
/
JsonResponseTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<?php
/*
* This file is part of the jiannei/laravel-response.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Jiannei\Response\Laravel\Support\Traits;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\AbstractPaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
trait JsonResponseTrait
{
/**
* Respond with an accepted response and associate a location and/or content if provided.
*
* @param array $data
* @param string $message
* @param string $location
* @return JsonResponse|JsonResource
*/
public function accepted($data = [], string $message = '', string $location = '')
{
$response = $this->success($data, $message, 202);
if ($location) {
$response->header('Location', $location);
}
return $response;
}
/**
* Respond with a created response and associate a location if provided.
*
* @param null $data
* @param string $message
* @param string $location
* @return JsonResponse|JsonResource
*/
public function created($data = [], string $message = '', string $location = '')
{
$response = $this->success($data, $message, 201);
if ($location) {
$response->header('Location', $location);
}
return $response;
}
/**
* Respond with a no content response.
*
* @param string $message
* @return JsonResponse|JsonResource
*/
public function noContent(string $message = '')
{
return $this->success([], $message, 204);
}
/**
* Alias of success method, no need to specify data parameter.
*
* @param string $message
* @param int $code
* @param array $headers
* @param int $option
* @return JsonResponse|JsonResource
*/
public function ok(string $message = '', int $code = 200, array $headers = [], int $option = 0)
{
return $this->success([], $message, $code, $headers, $option);
}
/**
* Alias of the successful method, no need to specify the message and data parameters.
* You can use ResponseCodeEnum to localize the message.
*
* @param int $code
* @param array $headers
* @param int $option
* @return JsonResponse|JsonResource
*/
public function localize(int $code = 200, array $headers = [], int $option = 0)
{
return $this->ok('', $code, $headers, $option);
}
/**
* Return a 400 bad request error.
*
* @param string|null $message
*/
public function errorBadRequest(string $message = '')
{
$this->fail($message, 400);
}
/**
* Return a 401 unauthorized error.
*
* @param string $message
*/
public function errorUnauthorized(string $message = '')
{
$this->fail($message, 401);
}
/**
* Return a 403 forbidden error.
*
* @param string $message
*/
public function errorForbidden(string $message = '')
{
$this->fail($message, 403);
}
/**
* Return a 404 not found error.
*
* @param string $message
*/
public function errorNotFound(string $message = '')
{
$this->fail($message, 404);
}
/**
* Return a 405 method not allowed error.
*
* @param string $message
*/
public function errorMethodNotAllowed(string $message = '')
{
$this->fail($message, 405);
}
/**
* Return a 500 internal server error.
*
* @param string $message
*/
public function errorInternal(string $message = '')
{
$this->fail($message);
}
/**
* Return an fail response.
*
* @param string $message
* @param int $code
* @param array|null $errors
* @param array $header
* @param int $options
* @return JsonResponse
*
* @throws HttpResponseException
*/
public function fail(string $message = '', int $code = 500, $errors = null, array $header = [], int $options = 0)
{
$response = $this->response(
$this->formatData(null, $message, $code, $errors),
Config::get('response.error_code') ?: $code,
$header,
$options
);
if (is_null($errors)) {
$response->throwResponse();
}
return $response;
}
/**
* Return an success response.
*
* @param JsonResource|array|mixed $data
* @param string $message
* @param int $code
* @param array $headers
* @param int $option
* @return JsonResponse|JsonResource
*/
public function success($data = [], string $message = '', int $code = 200, array $headers = [], int $option = 0)
{
if ($data instanceof ResourceCollection) {
return $this->formatResourceCollectionResponse(...func_get_args());
}
if ($data instanceof JsonResource) {
return $this->formatResourceResponse(...func_get_args());
}
if ($data instanceof AbstractPaginator) {
return $this->formatPaginatedResponse(...func_get_args());
}
if ($data instanceof Arrayable) {
$data = $data->toArray();
}
return $this->formatArrayResponse(Arr::wrap($data), $message, $code, $headers, $option);
}
/**
* Format normal array data.
*
* @param array|null $data
* @param string $message
* @param int $code
* @param array $headers
* @param int $option
* @return JsonResponse
*/
protected function formatArrayResponse(array $data, string $message = '', int $code = 200, array $headers = [], int $option = 0): JsonResponse
{
return $this->response($this->formatData($data, $message, $code), $code, $headers, $option);
}
/**
* Format response data fields.
*
* @param array $responseData
* @param array $dataFieldsConfig
* @return array
*/
protected function formatDataFields(array $responseData, array $dataFieldsConfig = []): array
{
if (empty($dataFieldsConfig)) {
return $responseData;
}
foreach ($responseData as $field => $value) {
$fieldConfig = Arr::get($dataFieldsConfig, $field);
if (is_null($fieldConfig)) {
continue;
}
if ($value && is_array($value) && in_array($field, ['data', 'meta', 'pagination', 'links'])) {
$value = $this->formatDataFields($value, Arr::get($dataFieldsConfig, "{$field}.fields", []));
}
$alias = $fieldConfig['alias'] ?? $field;
$show = $fieldConfig['show'] ?? true;
$map = $fieldConfig['map'] ?? null;
unset($responseData[$field]);
if ($show) {
$responseData[$alias] = $map[$value] ?? $value;
}
}
return $responseData;
}
/**
* Format return data structure.
*
* @param JsonResource|array|null $data
* @param $message
* @param $code
* @param null $errors
* @return array
*/
protected function formatData($data, $message, &$code, $errors = null): array
{
$originalCode = $code;
$code = (int) substr($code, 0, 3); // notice
if ($code >= 400 && $code <= 499) {// client error
$status = 'error';
} elseif ($code >= 500 && $code <= 599) {// service error
$status = 'fail';
} else {
$status = 'success';
}
if (! $message && class_exists($enumClass = Config::get('response.enum'))) {
$message = $enumClass::fromValue($originalCode)->description;
}
return $this->formatDataFields([
'status' => $status,
'code' => $originalCode,
'message' => $message,
'data' => $data ?: (object) $data,
'error' => $errors ?: (object) [],
], Config::get('response.format.fields', []));
}
/**
* Format paginated response.
*
* @param AbstractPaginator $resource
* @param string $message
* @param int $code
* @param array $headers
* @param int $option
* @return mixed
*/
protected function formatPaginatedResponse($resource, string $message = '', $code = 200, array $headers = [], $option = 0)
{
$paginated = $resource->toArray();
$paginationInformation = $this->formatPaginatedData($paginated);
$data = array_merge_recursive(['data' => $paginated['data']], $paginationInformation);
return $this->response($this->formatData($data, $message, $code), $code, $headers, $option);
}
/**
* Format paginated data.
*
* @param array $paginated
* @return array
*/
protected function formatPaginatedData(array $paginated)
{
return [
'meta' => [
'pagination' => [
'total' => $paginated['total'] ?? 0,
'count' => $paginated['to'] ?? 0,
'per_page' => $paginated['per_page'] ?? 0,
'current_page' => $paginated['current_page'] ?? 0,
'total_pages' => $paginated['last_page'] ?? 0,
'links' => [
'previous' => $paginated['prev_page_url'] ?? '',
'next' => $paginated['next_page_url'] ?? '',
],
],
],
];
}
/**
* Format collection resource response.
*
* @param JsonResource $resource
* @param string $message
* @param int $code
* @param array $headers
* @param int $option
* @return mixed
*/
protected function formatResourceCollectionResponse($resource, string $message = '', int $code = 200, array $headers = [], int $option = 0)
{
$data = array_merge_recursive(['data' => $resource->resolve(request())], $resource->with(request()), $resource->additional);
if ($resource->resource instanceof AbstractPaginator) {
$paginated = $resource->resource->toArray();
$paginationInformation = $this->formatPaginatedData($paginated);
$data = array_merge_recursive($data, $paginationInformation);
}
return tap(
$this->response($this->formatData($data, $message, $code), $code, $headers, $option),
function ($response) use ($resource) {
$response->original = $resource->resource->map(
function ($item) {
return is_array($item) ? Arr::get($item, 'resource') : $item->resource;
}
);
$resource->withResponse(request(), $response);
}
);
}
/**
* Format JsonResource Data.
*
* @param JsonResource $resource
* @param string $message
* @param int $code
* @param array $headers
* @param int $option
* @return mixed
*/
protected function formatResourceResponse($resource, string $message = '', $code = 200, array $headers = [], $option = 0)
{
$resourceData = array_merge_recursive($resource->resolve(request()), $resource->with(request()), $resource->additional);
return tap(
$this->response($this->formatData($resourceData, $message, $code), $code, $headers, $option),
function ($response) use ($resource) {
$response->original = $resource->resource;
$resource->withResponse(request(), $response);
}
);
}
/**
* Return a new JSON response from the application.
*
* @param mixed $data
* @param int $status
* @param array $headers
* @param int $options
* @return JsonResponse
*/
protected function response($data = [], int $status = 200, array $headers = [], int $options = 0): JsonResponse
{
return new JsonResponse($data, $status, $headers, $options);
}
}