Completed
Branch dev (20d83f)
by Arina
01:20
created

JsonResourceTransformer::objectClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace ArinaSystems\JsonResponse\Transformers;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Pagination\LengthAwarePaginator;
7
use ArinaSystems\JsonResponse\Facades\JsonResponse;
8
9
class JsonResourceTransformer extends Transformer
10
{
11
    /**
12
     * Determine which class of object should be transform.
13
     *
14
     * @return string
15
     */
16
    public function objectClass(): string
17
    {
18
        return \Illuminate\Http\Resources\Json\JsonResource::class;
19
    }
20
21
    /**
22
     * Transform the data value to array.
23
     *
24
     * @return array
25
     */
26
    public function toArray(): array
27
    {
28
        if ($this->item->resource instanceof LengthAwarePaginator) {
29
            $this->paginationInformation();
30
        }
31
32
        return $this->item->resolve();
33
    }
34
35
    /**
36
     * Add the pagination information to the response.
37
     *
38
     * @return void
39
     */
40
    protected function paginationInformation()
41
    {
42
        $paginated = $this->item->resource->toArray();
43
44
        JsonResponse::setAttributes('links', $this->paginationLinks($paginated));
45
        JsonResponse::setAttributes('meta', $this->meta($paginated));
46
    }
47
48
    /**
49
     * Get the pagination links for the response.
50
     *
51
     * @param  array   $paginated
52
     * @return array
53
     */
54
    protected function paginationLinks($paginated)
55
    {
56
        return [
57
            'first' => $paginated['first_page_url'] ?? null,
58
            'last'  => $paginated['last_page_url'] ?? null,
59
            'prev'  => $paginated['prev_page_url'] ?? null,
60
            'next'  => $paginated['next_page_url'] ?? null,
61
        ];
62
    }
63
64
    /**
65
     * Gather the meta data for the response.
66
     *
67
     * @param  array   $paginated
68
     * @return array
69
     */
70
    protected function meta($paginated)
71
    {
72
        return Arr::except($paginated, [
73
            'data',
74
            'first_page_url',
75
            'last_page_url',
76
            'prev_page_url',
77
            'next_page_url',
78
        ]);
79
    }
80
}
81