Completed
Pull Request — master (#119)
by Toby
08:33 queued 03:25
created

Document::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of JSON-API.
5
 *
6
 * (c) Toby Zerner <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Tobscure\JsonApi;
13
14
use JsonSerializable;
15
16
class Document implements JsonSerializable
17
{
18
    use LinksTrait;
19
    use MetaTrait;
20
21
    const MEDIA_TYPE = 'application/vnd.api+json';
22
23
    /**
24
     * The data object.
25
     *
26
     * @var ResourceInterface|ResourceInterface[]|null
27
     */
28
    protected $data;
29
30
    /**
31
     * The errors array.
32
     *
33
     * @var array|null
34
     */
35
    protected $errors;
36
37
    /**
38
     * The jsonapi array.
39
     *
40
     * @var array|null
41
     */
42
    protected $jsonapi;
43
44
    /**
45
     * Relationships to include.
46
     *
47
     * @var array
48
     */
49
    protected $include = [];
50
51
    /**
52 12
     * Sparse fieldsets.
53
     *
54 12
     * @var array
55 12
     */
56
    protected $fields = [];
57
58
    /**
59
     * @param ResourceInterface|ResourceInterface[] $data
0 ignored issues
show
Documentation introduced by
Should the type for parameter $data not be ResourceInterface|ResourceInterface[]|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
60
     */
61
    public function __construct($data = null)
62
    {
63
        $this->data = $data;
64
    }
65 9
66
    /**
67 9
     * Get the data object.
68
     *
69 9
     * @return ResourceInterface|ResourceInterface[]|null $data
70 9
     */
71
    public function getData()
72
    {
73
        return $this->data;
74 9
    }
75 3
76 3
    /**
77 9
     * Set the data object.
78 9
     *
79
     * @param ResourceInterface|ResourceInterface[]|null $data
80
     *
81 9
     * @return $this
82 3
     */
83
    public function setData($data)
84 3
    {
85
        $this->data = $data;
86
87
        return $this;
88 3
    }
89
90
    /**
91
     * Get the errors array.
92 3
     *
93
     * @return array|null $errors
94
     */
95
    public function getErrors()
96 3
    {
97 3
        return $this->errors;
98 9
    }
99 9
100
    /**
101 9
     * Set the errors array.
102
     *
103
     * @param array|null $errors
104 3
     *
105 9
     * @return $this
106
     */
107 9
    public function setErrors(array $errors = null)
108
    {
109
        $this->errors = $errors;
110
111
        return $this;
112
    }
113
114
    /**
115
     * Get the jsonapi array.
116 3
     *
117
     * @return array|null $jsonapi
118 3
     */
119 3
    public function getJsonapi()
120
    {
121 3
        return $this->jsonapi;
122
    }
123
124 3
    /**
125
     * Set the jsonapi array.
126
     *
127 3
     * @param array|null $jsonapi
128
     *
129
     * @return $this
130
     */
131
    public function setJsonapi(array $jsonapi = null)
132
    {
133
        $this->jsonapi = $jsonapi;
134
135
        return $this;
136
    }
137
138
    /**
139
     * Get the relationships to include.
140
     *
141
     * @return array $include
142
     */
143
    public function getInclude()
144
    {
145
        return $this->include;
146
    }
147
148
    /**
149
     * Set the relationships to include.
150
     *
151
     * @param array $include
152
     *
153
     * @return $this
154
     */
155
    public function setInclude(array $include)
156
    {
157
        $this->include = $include;
158
159
        return $this;
160
    }
161
162
    /**
163
     * Get the sparse fieldsets.
164
     *
165
     * @return array $fields
166
     */
167
    public function getFields()
168
    {
169
        return $this->fields;
170
    }
171
172
    /**
173
     * Set the sparse fieldsets.
174
     *
175
     * @param array $fields
176
     *
177 12
     * @return $this
178
     */
179 12
    public function setFields(array $fields)
180
    {
181 12
        $this->fields = $fields;
182
183
        return $this;
184
    }
185 12
186 9
    /**
187
     * Build the JSON-API document as an array.
188 9
     *
189
     * @return array
190 9
     */
191 3
    public function toArray()
192 3
    {
193 3
        $document = [];
194 3
195 9
        if ($this->links) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->links of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
196
            $document['links'] = $this->links;
197 12
        }
198
199
        if ($this->data) {
200
            $isCollection = is_array($this->data);
201 12
202
            // Build a multi-dimensional map of all of the distinct resources
203
            // that are present in the document, indexed by type and ID. This is
204
            // done by recursively looping through each of the resources and
205 12
            // their included relationships. We do this so that any resources
206
            // that are duplicated may be merged back into a single instance.
207
            $map = [];
208
            $resources = $isCollection ? $this->data : [$this->data];
209 12
210
            $this->addResourcesToMap($map, $resources, $this->include);
211
212
            // Now extract the document's primary resource(s) from the resource
213
            // map, and flatten the map's remaining resources to be included in
214
            // the document's "included" array.
215
            foreach ($resources as $resource) {
216
                $type = $resource->getType();
217 6
                $id = $resource->getId();
218
219 6
                $primary[] = $map[$type][$id];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$primary was never initialized. Although not strictly required by PHP, it is generally a good practice to add $primary = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
220
                unset($map[$type][$id]);
221
            }
222
223
            $included = call_user_func_array('array_merge', $map);
224
225
            $document['data'] = $isCollection ? $primary : $primary[0];
0 ignored issues
show
Bug introduced by
The variable $primary does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
226
227
            if ($included) {
228
                $document['included'] = $included;
229
            }
230
        }
231
232
        if ($this->meta) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->meta of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
233
            $document['meta'] = $this->meta;
234
        }
235
236
        if ($this->errors) {
237
            $document['errors'] = $this->errors;
238
        }
239
240
        if ($this->jsonapi) {
241
            $document['jsonapi'] = $this->jsonapi;
242
        }
243
244
        return $document;
245
    }
246
247
    /**
248
     * Build the JSON-API document and encode it as a JSON string.
249
     *
250
     * @return string
251
     */
252
    public function __toString()
253
    {
254
        return json_encode($this->toArray());
255
    }
256
257
    /**
258
     * Serialize for JSON usage.
259
     *
260
     * @return array
261
     */
262
    public function jsonSerialize()
263
    {
264
        return $this->toArray();
265
    }
266
267
    /**
268
     * Recursively add the given resources and their relationships to a map.
269
     *
270
     * @param array &$map The map to merge resources into.
271
     * @param ResourceInterface[] $resources
272
     * @param array $include An array of relationship paths to include.
273
     */
274
    private function addResourcesToMap(array &$map, array $resources, array $include)
275
    {
276
        // Index relationship paths so that we have a list of the direct
277
        // relationships that will be included on these resources, and arrays
278
        // of their respective nested relationships.
279
        $include = $this->indexRelationshipPaths($include);
280
281
        foreach ($resources as $resource) {
282
            $relationships = [];
283
284
            // Get each of the relationships we're including on this resource,
285
            // and add their resources (and their relationships, and so on) to
286
            // the map.
287
            foreach ($include as $name => $nested) {
288
                if (! ($relationship = $resource->getRelationship($name))) {
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $relationship is correct as $resource->getRelationship($name) (which targets Tobscure\JsonApi\Resourc...face::getRelationship()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
289
                    continue;
290
                }
291
292
                $relationships[$name] = $relationship;
293
294
                if ($data = $relationship->getData()) {
295
                    $children = is_array($data) ? $data : [$data];
296
297
                    $this->addResourcesToMap($map, $children, $nested);
298
                }
299
            }
300
301
            // Serialize the resource into an array and add it to the map. If
302
            // it is already present, its properties will be merged into the
303
            // existing resource.
304
            $this->addResourceToMap($map, $resource, $relationships);
305
        }
306
    }
307
308
    /**
309
     * Serialize the given resource as an array and add it to the given map.
310
     *
311
     * If it is already present in the map, its properties will be merged into
312
     * the existing array.
313
     *
314
     * @param array &$map
315
     * @param ResourceInterface $resource
316
     * @param Relationship[] $resource
317
     */
318
    private function addResourceToMap(array &$map, ResourceInterface $resource, array $relationships)
319
    {
320
        $type = $resource->getType();
321
        $id = $resource->getId();
322
323
        if (empty($map[$type][$id])) {
324
            $map[$type][$id] = [
325
                'type' => $type,
326
                'id' => $id
327
            ];
328
        }
329
330
        $array = &$map[$type][$id];
331
        $fields = $this->getFieldsForType($type);
332
333 View Code Duplication
        if ($meta = $resource->getMeta()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
334
            $array['meta'] = array_replace_recursive(isset($array['meta']) ? $array['meta'] : [], $meta);
335
        }
336
337 View Code Duplication
        if ($links = $resource->getLinks()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
338
            $array['links'] = array_replace_recursive(isset($array['links']) ? $array['links'] : [], $links);
339
        }
340
341
        if ($attributes = $resource->getAttributes($fields)) {
342
            if ($fields) {
343
                $attributes = array_intersect_key($attributes, array_flip($fields));
344
            }
345
            if ($attributes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $attributes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
346
                $array['attributes'] = array_replace_recursive(isset($array['attributes']) ? $array['attributes'] : [], $attributes);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
347
            }
348
        }
349
350
        if ($relationships && $fields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $relationships of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
351
            $relationships = array_intersect_key($relationships, array_flip($fields));
352
        }
353
        if ($relationships) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $relationships of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
354
            $relationships = array_map(function ($relationship) {
355
                return $relationship->toArray();
356
            }, $relationships);
357
358
            $array['relationships'] = array_replace_recursive(isset($array['relationships']) ? $array['relationships'] : [], $relationships);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 141 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
359
        }
360
    }
361
362
    /**
363
     * Index relationship paths by top-level relationships.
364
     *
365
     * Given an array of relationship paths such as:
366
     *
367
     * ['user', 'user.employer', 'user.employer.country', 'comments']
368
     *
369
     * Returns an array with key-value pairs of top-level relationships and
370
     * their nested relationships:
371
     *
372
     * ['user' => ['employer', 'employer.country'], 'comments' => []]
373
     *
374
     * @param array $paths
375
     *
376
     * @return array
377
     */
378
    private function indexRelationshipPaths(array $paths)
379
    {
380
        $tree = [];
381
382
        foreach ($paths as $path) {
383
            list($primary, $nested) = array_pad(explode('.', $path, 2), 2, null);
384
385
            if (! isset($tree[$primary])) {
386
                $tree[$primary] = [];
387
            }
388
389
            if ($nested) {
390
                $tree[$primary][] = $nested;
391
            }
392
        }
393
394
        return $tree;
395
    }
396
397
    /**
398
     * Get the fields that should be included for resources of the given type.
399
     *
400
     * @param string $type
401
     *
402
     * @return array|null
403
     */
404
    private function getFieldsForType($type)
405
    {
406
        return isset($this->fields[$type]) ? $this->fields[$type] : null;
407
    }
408
}
409