Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Illuminate\Http\Resources\Json;
4
 
5
use Illuminate\Support\Arr;
6
 
7
class PaginatedResourceResponse extends ResourceResponse
8
{
9
    /**
10
     * Create an HTTP response that represents the object.
11
     *
12
     * @param  \Illuminate\Http\Request  $request
13
     * @return \Illuminate\Http\JsonResponse
14
     */
15
    public function toResponse($request)
16
    {
17
        return tap(response()->json(
18
            $this->wrap(
19
                $this->resource->resolve($request),
20
                array_merge_recursive(
21
                    $this->paginationInformation($request),
22
                    $this->resource->with($request),
23
                    $this->resource->additional
24
                )
25
            ),
26
            $this->calculateStatus(),
27
            [],
28
            $this->resource->jsonOptions()
29
        ), function ($response) use ($request) {
30
            $response->original = $this->resource->resource->map(function ($item) {
31
                return is_array($item) ? Arr::get($item, 'resource') : $item->resource;
32
            });
33
 
34
            $this->resource->withResponse($request, $response);
35
        });
36
    }
37
 
38
    /**
39
     * Add the pagination information to the response.
40
     *
41
     * @param  \Illuminate\Http\Request  $request
42
     * @return array
43
     */
44
    protected function paginationInformation($request)
45
    {
46
        $paginated = $this->resource->resource->toArray();
47
 
48
        $default = [
49
            'links' => $this->paginationLinks($paginated),
50
            'meta' => $this->meta($paginated),
51
        ];
52
 
53
        if (method_exists($this->resource, 'paginationInformation')) {
54
            return $this->resource->paginationInformation($request, $paginated, $default);
55
        }
56
 
57
        return $default;
58
    }
59
 
60
    /**
61
     * Get the pagination links for the response.
62
     *
63
     * @param  array  $paginated
64
     * @return array
65
     */
66
    protected function paginationLinks($paginated)
67
    {
68
        return [
69
            'first' => $paginated['first_page_url'] ?? null,
70
            'last' => $paginated['last_page_url'] ?? null,
71
            'prev' => $paginated['prev_page_url'] ?? null,
72
            'next' => $paginated['next_page_url'] ?? null,
73
        ];
74
    }
75
 
76
    /**
77
     * Gather the meta data for the response.
78
     *
79
     * @param  array  $paginated
80
     * @return array
81
     */
82
    protected function meta($paginated)
83
    {
84
        return Arr::except($paginated, [
85
            'data',
86
            'first_page_url',
87
            'last_page_url',
88
            'prev_page_url',
89
            'next_page_url',
90
        ]);
91
    }
92
}