Passed
Push — develop ( 7f9ed1...7fd325 )
by Alex
02:45
created

JsonApiTransforms::transformRelationship()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 7
nc 3
nop 2
1
<?php
2
3
namespace Huntie\JsonApi\Support;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Pagination\LengthAwarePaginator;
7
use Illuminate\Support\Collection;
8
9
/**
10
 * Transform Eloquent models and collections into JSON API objects.
11
 */
12
trait JsonApiTransforms
13
{
14
    /**
15
     * Transform a model instance into a JSON API object.
16
     *
17
     * @param Model      $record
18
     * @param array|null $fields  Field subset to return
19
     * @param array|null $include Relations to include
20
     *
21
     * @return array
22
     */
23
    protected function transformRecord($record, array $fields = [], array $include = [])
24
    {
25
        $relations = array_unique(array_merge($record->getRelations(), $include));
26
        $record = $record->load($relations);
27
28
        $attributes = $record->toArray();
29
        $relationships = [];
30
        $included = [];
31
32
        foreach ($relations as $relation) {
33
            $relationships[$relation] = $this->transformRelationship($record, $relation);
34
35
            if (in_array($relation, $include)) {
36
                if ($record->{$relation} instanceof Collection) {
37
                    $included = array_merge($included, $this->transformCollectionSimple($record->{$relation})['data']);
38
                } else if ($record->{$relation} instanceof Model) {
39
                    $included = array_merge($included, $this->transformRecordSimple($record->{$relation})['data']);
40
                }
41
            }
42
        }
43
44
        array_forget($attributes, $relations);
45
        $included = array_filter($included);
46
47
        if (!empty($fields)) {
48
            $attributes = array_only($attributes, $fields);
49
        }
50
51
        $data = array_filter([
52
            'type' => $record->getTable(),
53
            'id' => $record->id,
54
            'attributes' => array_except($attributes, ['id']),
55
            'relationships' => $relationships,
56
        ]);
57
58
        return array_filter(compact('data', 'included'));
59
    }
60
61
    /**
62
     * Transform a model instance into a JSON API object without additonal data.
63
     *
64
     * @param Model $record
65
     *
66
     * @return array
67
     */
68
    protected function transformRecordSimple($record)
69
    {
70
        $attributes = array_diff_key($record->toArray(), $record->getRelations());
71
        $attributes = array_except($attributes, ['id']);
72
73
        return [
74
            'data' => [
75
                'type' => $record->getTable(),
76
                'id' => $record->id,
77
                'attributes' => $attributes,
78
            ]
79
        ];
80
    }
81
82
    /**
83
     * Transform a model instance into a JSON API resource identifier.
84
     *
85
     * @param Model $record
86
     *
87
     * @return array
88
     */
89
    protected function transformRecordIdentifier($record)
0 ignored issues
show
Unused Code introduced by
The parameter $record 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...
90
    {
91
        return [
92
            'data' => [
93
                'type' => $relatedRecord->getTable(),
0 ignored issues
show
Bug introduced by
The variable $relatedRecord does not exist. Did you mean $record?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
94
                'id' => $relatedRecord->id,
0 ignored issues
show
Bug introduced by
The variable $relatedRecord does not exist. Did you mean $record?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
95
            ]
96
        ];
97
    }
98
99
    /**
100
     * Transform a set of models into a JSON API collection.
101
     *
102
     * @param Collection|LengthAwarePaginator $records
103
     * @param array                           $fields
104
     *
105
     * @return array
106
     */
107
    protected function transformCollection($records, array $fields = [])
108
    {
109
        $data = $records->map(function ($record) use ($fields) {
0 ignored issues
show
Bug introduced by
The method map does only exist in Illuminate\Support\Collection, but not in Illuminate\Pagination\LengthAwarePaginator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
110
            return $this->transformRecord($record, $fields)['data'];
111
        })->toArray();
112
113
        $links = [];
114
115
        if ($records instanceof LengthAwarePaginator) {
116
            $links['first'] = $records->url(1);
117
            $links['last'] = $records->url($records->lastPage());
118
            $links['prev'] = $records->previousPageUrl();
119
            $links['next'] = $records->nextPageUrl();
120
        }
121
122
        return array_merge(compact('data'), array_filter(compact('links')));
123
    }
124
125
    /**
126
     * Transform a set of models into a JSON API collection without additional data.
127
     *
128
     * @param Collection $records
129
     *
130
     * @return array
131
     */
132
    protected function transformCollectionSimple($records)
133
    {
134
        $data = $records->map(function ($record) {
135
            return $this->transformRecordSimple($record)['data'];
136
        })->toArray();
137
138
        return compact('data');
139
    }
140
141
    /**
142
     * Transform a set of models into a collection of JSON API resource
143
     * identifier objects.
144
     *
145
     * @param Collection $records
146
     *
147
     * @return array
148
     */
149
    protected function transformCollectionIdentifiers($records)
150
    {
151
        $data = $records->map(function ($record) {
152
            return $this->transformRecordIdentifier($record)['data'];
153
        });
154
155
        return compact('data');
156
    }
157
158
    /**
159
     * Transform a model relationship into a single, or collection of, JSON API
160
     * resource identifier objects.
161
     *
162
     * @param Model  $record
163
     * @param string $relation
164
     *
165
     * @return array
166
     */
167
    protected function transformRelationship($record, $relation)
168
    {
169
        $data = null;
170
171
        if ($record->{$relation} instanceof Collection) {
172
            return $this->transformCollectionIdentifiers($record->{$relation});
173
        } else if ($record->{$relation} instanceof Model) {
174
            return $this->transformRecordIdentifier($record->{$relation});
175
        }
176
177
        return compact('data');
178
    }
179
}
180