Completed
Push — develop ( aa0b1d...677315 )
by Alex
02:08
created

JsonApiController::transformCollection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace Huntie\JsonApi\Http\Controllers;
4
5
use Huntie\JsonApi\Support\JsonApiErrors;
6
use Huntie\JsonApi\Http\JsonApiResponse;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Http\Request;
9
use Illuminate\Routing\Controller;
10
11
abstract class JsonApiController extends Controller
12
{
13
    use JsonApiErrors;
14
15
    /**
16
     * Return the Eloquent Model for the resource.
17
     *
18
     * @return Model
19
     */
20
    abstract protected function getModel();
21
22
    /**
23
     * Return the type name of the resource.
24
     *
25
     * @return string
26
     */
27
    protected function getModelType()
28
    {
29
        return $this->getModel()->getTable();
30
    }
31
32
    /**
33
     * Return a listing of the resource.
34
     *
35
     * @param Request $request
36
     *
37
     * @return JsonApiResponse
38
     */
39
    public function indexAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
40
    {
41
        $records = $this->getModel()->all();
42
43
        return new JsonApiResponse($this->transformCollection($records));
44
    }
45
46
    /**
47
     * Return a specified record.
48
     *
49
     * @param Request   $request
50
     * @param Model|int $record
51
     *
52
     * @return JsonApiResponse
53
     */
54
    public function showAction(Request $request, $record)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
55
    {
56
        $record = $record instanceof Model ? $record : $this->findModelInstance($record);
57
58
        return new JsonApiResponse($this->transformRecord($record));
59
    }
60
61
    /**
62
     * Return an instance of the resource by primary key.
63
     *
64
     * @param mixed $key
65
     *
66
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
67
     *
68
     * @return Model
69
     */
70
    protected function findModelInstance($key)
71
    {
72
        return $this->getModel()->findOrFail($key);
73
    }
74
75
    /**
76
     * Transform a set of models into a JSON API collection.
77
     *
78
     * @param \Illuminate\Support\Collection $records
79
     * @param array                          $fields
80
     *
81
     * @return array
82
     */
83
    protected function transformCollection($records, array $fields = [])
84
    {
85
        $data = [];
86
87
        foreach ($records as $record) {
88
            $data[] = $this->transformRecord($record, $fields)['data'];
89
        }
90
91
        return compact('data');
92
    }
93
94
    /**
95
     * Transform a model instance into a JSON API object.
96
     *
97
     * @param Model      $record
98
     * @param array|null $fields  Field names of attributes to limit to
99
     * @param array|null $include Relations to include
100
     *
101
     * @return array
102
     */
103
    protected function transformRecord($record, array $fields = [], array $include = [])
104
    {
105
        $relations = array_merge($record->getRelations(), $include);
106
        $attributes = $record->load($relations)->toArray();
107
        $relationships = [];
108
        $included = [];
109
110
        foreach ($relations as $relation) {
111
            $relationships[$relation] = [
112
                'data' => []
113
            ];
114
115
            foreach (array_pull($attributes, $relation) as $relatedRecord) {
116
                $relationships[$relation]['data'][] = [
117
                    'type' => $relation,
118
                    'id' => $relatedRecord['id'],
119
                ];
120
121
                if (in_array($relation, $include)) {
122
                    $included[] = [
123
                        'type' => $relation,
124
                        'id' => $relatedRecord['id'],
125
                        'attributes' => array_except($relatedRecord, ['id']),
126
                    ];
127
                }
128
            }
129
        }
130
131
        if (!empty($fields)) {
132
            $attributes = array_only($attributes, $fields);
133
        }
134
135
        $data = [
136
            'type' => $record->getTable(),
137
            'id' => $record->id,
138
            'attributes' => array_except($attributes, ['id']),
139
        ];
140
141
        if (!empty($relationships)) {
142
            $data['relationships'] = $relationships;
143
        }
144
145
        return !empty($included) ? compact('data', 'included') : compact('data');
146
    }
147
}
148