1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Longman\LaravelLodash\Http\Resources\Response; |
6
|
|
|
|
7
|
|
|
use Illuminate\Http\JsonResponse; |
8
|
|
|
use Illuminate\Http\Resources\Json\PaginatedResourceResponse as BasePaginatedResourceResponse; |
9
|
|
|
use Illuminate\Support\Arr; |
10
|
|
|
|
11
|
|
|
use function array_merge_recursive; |
12
|
|
|
use function count; |
13
|
|
|
use function is_array; |
14
|
|
|
use function response; |
15
|
|
|
use function tap; |
16
|
|
|
|
17
|
|
|
// phpcs:disable SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse |
18
|
|
|
use const JSON_UNESCAPED_SLASHES; |
19
|
|
|
use const JSON_UNESCAPED_UNICODE; |
20
|
|
|
|
21
|
|
|
// phpcs:enable |
22
|
|
|
|
23
|
|
|
class PaginatedResourceResponse extends BasePaginatedResourceResponse |
24
|
|
|
{ |
25
|
|
|
public function toResponse($request): JsonResponse |
26
|
|
|
{ |
27
|
|
|
$jsonOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; |
28
|
|
|
|
29
|
|
|
return tap(response()->json( |
30
|
|
|
$this->wrap( |
31
|
|
|
$this->resource->resolve($request), |
32
|
|
|
array_merge_recursive( |
33
|
|
|
$this->paginationInformation($request), |
34
|
|
|
$this->resource->with($request), |
35
|
|
|
$this->resource->additional, |
36
|
|
|
), |
|
|
|
|
37
|
|
|
), |
38
|
|
|
$this->calculateStatus(), |
39
|
|
|
[], |
40
|
|
|
$jsonOptions, |
41
|
|
|
), function ($response) use ($request) { |
42
|
|
|
$response->original = $this->resource->resource->map(static function ($item) { |
43
|
|
|
return is_array($item) ? Arr::get($item, 'resource') : $item->resource; |
44
|
|
|
}); |
45
|
|
|
|
46
|
|
|
$this->resource->withResponse($request, $response); |
47
|
|
|
}); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function paginationInformation($request): array |
51
|
|
|
{ |
52
|
|
|
$paginated = $this->resource->resource->toArray(); |
53
|
|
|
|
54
|
|
|
return [ |
55
|
|
|
'meta' => $this->meta($paginated), |
56
|
|
|
]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
protected function meta($paginated): array |
60
|
|
|
{ |
61
|
|
|
return [ |
62
|
|
|
'pagination' => [ |
63
|
|
|
'total' => $paginated['total'] ?? null, |
64
|
|
|
'count' => count($paginated['data']) ?? null, |
65
|
|
|
'perPage' => $paginated['per_page'], |
66
|
|
|
'currentPage' => $paginated['current_page'] ?? null, |
67
|
|
|
'totalPages' => $paginated['last_page'] ?? null, |
68
|
|
|
'links' => [ |
69
|
|
|
'next' => $paginated['next_page_url'] ?? null, |
70
|
|
|
'previous' => $paginated['prev_page_url'] ?? null, |
71
|
|
|
], |
72
|
|
|
], |
73
|
|
|
]; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|