Completed
Pull Request — master (#284)
by
unknown
04:32 queued 01:41
created

JsonApiSerializer::isRootObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the League\Fractal package.
5
 *
6
 * (c) Phil Sturgeon <[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 League\Fractal\Serializer;
13
14
use InvalidArgumentException;
15
use League\Fractal\Pagination\PaginatorInterface;
16
use League\Fractal\Resource\ResourceInterface;
17
18
class JsonApiSerializer extends ArraySerializer
19
{
20
    protected $baseUrl;
21
    protected $rootObjects;
22
23
    /**
24
     * JsonApiSerializer constructor.
25
     *
26
     * @param string $baseUrl
27
     */
28 27
    public function __construct($baseUrl = null)
29
    {
30 27
        $this->baseUrl = $baseUrl;
31 27
        $this->rootObjects = [];
32 27
    }
33
34
    /**
35
     * Serialize a collection.
36
     *
37
     * @param string $resourceKey
38
     * @param array $data
39
     *
40
     * @return array
41
     */
42 17
    public function collection($resourceKey, array $data)
43
    {
44 17
        $resources = [];
45
46 17
        foreach ($data as $resource) {
47 16
            $resources[] = $this->item($resourceKey, $resource)['data'];
48 17
        }
49
50 17
        return ['data' => $resources];
51
    }
52
53
    /**
54
     * Serialize an item.
55
     *
56
     * @param string $resourceKey
57
     * @param array $data
58
     *
59
     * @return array
60
     */
61 27
    public function item($resourceKey, array $data)
62
    {
63 27
        $id = $this->getIdFromData($data);
64
65
        $resource = [
66
            'data' => [
67 26
                'type' => $resourceKey,
68 26
                'id' => "$id",
69 26
                'attributes' => $data,
70 26
            ],
71 26
        ];
72
73 26
        unset($resource['data']['attributes']['id']);
74
75 26
        if(isset($resource['data']['attributes']['links'])) {
76 1
            $custom_links = $data['links'];
77 1
            unset($resource['data']['attributes']['links']);
78 1
        }
79
80 26
        if ($this->shouldIncludeLinks()) {
81 9
            $resource['data']['links'] = [
82 9
                'self' => "{$this->baseUrl}/$resourceKey/$id",
83
            ];
84 9
            if(isset($custom_links)) {
85 1
                $resource['data']['links'] = array_merge($custom_links, $resource['data']['links']);
86 1
            }
87 9
        }
88
89 26
        return $resource;
90
    }
91
92
    /**
93
     * Serialize the paginator.
94
     *
95
     * @param PaginatorInterface $paginator
96
     *
97
     * @return array
98
     */
99 3
    public function paginator(PaginatorInterface $paginator)
100
    {
101 3
        $currentPage = (int)$paginator->getCurrentPage();
102 3
        $lastPage = (int)$paginator->getLastPage();
103
104
        $pagination = [
105 3
            'total' => (int)$paginator->getTotal(),
106 3
            'count' => (int)$paginator->getCount(),
107 3
            'per_page' => (int)$paginator->getPerPage(),
108 3
            'current_page' => $currentPage,
109 3
            'total_pages' => $lastPage,
110 3
        ];
111
112 3
        $pagination['links'] = [];
113
114 3
        $pagination['links']['self'] = $paginator->getUrl($currentPage);
115 3
        $pagination['links']['first'] = $paginator->getUrl(1);
116
117 3
        if ($currentPage > 1) {
118 2
            $pagination['links']['prev'] = $paginator->getUrl($currentPage - 1);
119 2
        }
120
121 3
        if ($currentPage < $lastPage) {
122 2
            $pagination['links']['next'] = $paginator->getUrl($currentPage + 1);
123 2
        }
124
125 3
        $pagination['links']['last'] = $paginator->getUrl($lastPage);
126
127 3
        return ['pagination' => $pagination];
128
    }
129
130
    /**
131
     * Serialize the meta.
132
     *
133
     * @param array $meta
134
     *
135
     * @return array
136
     */
137 26
    public function meta(array $meta)
138
    {
139 26
        if (empty($meta)) {
140 21
            return [];
141
        }
142
143 5
        $result['meta'] = $meta;
144
145 5
        if (array_key_exists('pagination', $result['meta'])) {
146 3
            $result['links'] = $result['meta']['pagination']['links'];
147 3
            unset($result['meta']['pagination']['links']);
148 3
        }
149
150 5
        return $result;
151
    }
152
153
    /**
154
     * @return array
155
     */
156 2
    public function null()
157
    {
158
        return [
159 2
            'data' => null,
160 2
        ];
161
    }
162
163
    /**
164
     * Serialize the included data.
165
     *
166
     * @param ResourceInterface $resource
167
     * @param array $data
168
     *
169
     * @return array
170
     */
171 26
    public function includedData(ResourceInterface $resource, array $data)
172
    {
173 26
        list($serializedData, $linkedIds) = $this->pullOutNestedIncludedData($data);
174
175 26
        foreach ($data as $value) {
176 26
            foreach ($value as $includeObject) {
177 15
                if ($this->isNull($includeObject) || $this->isEmpty($includeObject)) {
178 4
                    continue;
179
                }
180
181 13
                $includeObjects = $this->createIncludeObjects($includeObject);
182
183 13 View Code Duplication
                foreach ($includeObjects as $object) {
184 13
                    $includeType = $object['type'];
185 13
                    $includeId = $object['id'];
186 13
                    $cacheKey = "$includeType:$includeId";
187 13
                    if (!array_key_exists($cacheKey, $linkedIds)) {
188 13
                        $serializedData[] = $object;
189 13
                        $linkedIds[$cacheKey] = $object;
190 13
                    }
191 13
                }
192 26
            }
193 26
        }
194
195 26
        return empty($serializedData) ? [] : ['included' => $serializedData];
196
    }
197
198
    /**
199
     * Indicates if includes should be side-loaded.
200
     *
201
     * @return bool
202
     */
203 27
    public function sideloadIncludes()
204
    {
205 27
        return true;
206
    }
207
208
    /**
209
     * @param array $data
210
     * @param array $includedData
211
     *
212
     * @return array
213
     */
214 26
    public function injectData($data, $includedData)
215
    {
216 26
        $relationships = $this->parseRelationships($includedData);
217
218 26
        if (!empty($relationships)) {
219 15
            $data = $this->fillRelationships($data, $relationships);
220 15
        }
221
222 26
        return $data;
223
    }
224
225
    /**
226
     * Hook to manipulate the final sideloaded includes.
227
     * The JSON API specification does not allow the root object to be included
228
     * into the sideloaded `included`-array. We have to make sure it is
229
     * filtered out, in case some object links to the root object in a
230
     * relationship.
231
     *
232
     * @param array $includedData
233
     * @param array $data
234
     *
235
     * @return array
236
     */
237 26
    public function filterIncludes($includedData, $data)
238
    {
239 26
        if (!isset($includedData['included'])) {
240 13
            return $includedData;
241
        }
242
243
        // Create the RootObjects
244 13
        $this->createRootObjects($data);
245
246
        // Filter out the root objects
247 13
        $filteredIncludes = array_filter($includedData['included'], [$this, 'filterRootObject']);
248
249
        // Reset array indizes
250 13
        $includedData['included'] = array_merge([], $filteredIncludes);
251
252 13
        return $includedData;
253
    }
254
255
    /**
256
     * Filter function to delete root objects from array.
257
     *
258
     * @param array $object
259
     *
260
     * @return bool
261
     */
262 13
    protected function filterRootObject($object)
263
    {
264 13
        return !$this->isRootObject($object);
265
    }
266
267
    /**
268
     * Set the root objects of the JSON API tree.
269
     *
270
     * @param array $objects
271
     */
272
    protected function setRootObjects(array $objects = [])
273
    {
274 13
        $this->rootObjects = array_map(function ($object) {
275 13
            return "{$object['type']}:{$object['id']}";
276 13
        }, $objects);
277 13
    }
278
279
    /**
280
     * Determines whether an object is a root object of the JSON API tree.
281
     *
282
     * @param array $object
283
     *
284
     * @return bool
285
     */
286 13
    protected function isRootObject($object)
287
    {
288 13
        $objectKey = "{$object['type']}:{$object['id']}";
289 13
        return in_array($objectKey, $this->rootObjects);
290
    }
291
292
    /**
293
     * @param array $data
294
     *
295
     * @return bool
296
     */
297 15
    protected function isCollection($data)
298
    {
299 15
        return array_key_exists('data', $data) &&
300 15
        array_key_exists(0, $data['data']);
301
    }
302
303
    /**
304
     * @param array $data
305
     *
306
     * @return bool
307
     */
308 15
    protected function isNull($data)
309
    {
310 15
        return array_key_exists('data', $data) && $data['data'] === null;
311
    }
312
313
    /**
314
     * @param array $data
315
     *
316
     * @return bool
317
     */
318 14
    protected function isEmpty($data)
319
    {
320 14
        return array_key_exists('data', $data) && $data['data'] === [];
321
    }
322
323
    /**
324
     * @param array $data
325
     * @param array $relationships
326
     *
327
     * @return array
328
     */
329 15
    protected function fillRelationships($data, $relationships)
330
    {
331 15
        if ($this->isCollection($data)) {
332 7
            foreach ($relationships as $key => $relationship) {
333 7
                $data = $this->fillRelationshipAsCollection($data, $relationship, $key);
334 7
            }
335 7
        } else { // Single resource
336 10
            foreach ($relationships as $key => $relationship) {
337 10
                $data = $this->FillRelationshipAsSingleResource($data, $relationship, $key);
338 10
            }
339
        }
340
341 15
        return $data;
342
    }
343
344
    /**
345
     * @param array $includedData
346
     *
347
     * @return array
348
     */
349 26
    protected function parseRelationships($includedData)
350
    {
351 26
        $relationships = [];
352
353 26
        foreach ($includedData as $key => $inclusion) {
354 26
            foreach ($inclusion as $includeKey => $includeObject) {
355 15
                $relationships = $this->buildRelationships($includeKey, $relationships, $includeObject, $key);
356 26
            }
357 26
        }
358
359 26
        return $relationships;
360
    }
361
362
    /**
363
     * @param array $data
364
     *
365
     * @return integer
366
     */
367 27
    protected function getIdFromData(array $data)
368
    {
369 27
        if (!array_key_exists('id', $data)) {
370 1
            throw new InvalidArgumentException(
371
                'JSON API resource objects MUST have a valid id'
372 1
            );
373
        }
374 26
        return $data['id'];
375
    }
376
377
    /**
378
     * Keep all sideloaded inclusion data on the top level.
379
     *
380
     * @param array $data
381
     *
382
     * @return array
383
     */
384 26
    protected function pullOutNestedIncludedData(array $data)
385
    {
386 26
        $includedData = [];
387 26
        $linkedIds = [];
388
389 26
        foreach ($data as $value) {
390 26
            foreach ($value as $includeObject) {
391 15
                if (isset($includeObject['included'])) {
392 3 View Code Duplication
                    foreach ($includeObject['included'] as $object) {
393 3
                        $includeType = $object['type'];
394 3
                        $includeId = $object['id'];
395 3
                        $cacheKey = "$includeType:$includeId";
396
397 3
                        if (!array_key_exists($cacheKey, $linkedIds)) {
398 3
                            $includedData[] = $object;
399 3
                            $linkedIds[$cacheKey] = $object;
400 3
                        }
401 3
                    }
402 3
                }
403 26
            }
404 26
        }
405
406 26
        return [$includedData, $linkedIds];
407
    }
408
409
    /**
410
     * Whether or not the serializer should include `links` for resource objects.
411
     *
412
     * @return bool
413
     */
414 26
    protected function shouldIncludeLinks()
415
    {
416 26
        return $this->baseUrl !== null;
417
    }
418
419
    /**
420
     * Check if the objects are part of a collection or not
421
     *
422
     * @param $includeObject
423
     *
424
     * @return array
425
     */
426 13
    private function createIncludeObjects($includeObject)
427
    {
428 13
        if ($this->isCollection($includeObject)) {
429 7
            $includeObjects = $includeObject['data'];
430
431 7
            return $includeObjects;
432
        } else {
433 9
            $includeObjects = [$includeObject['data']];
434
435 9
            return $includeObjects;
436
        }
437
    }
438
439
    /**
440
     * Sets the RootObjects, either as collection or not.
441
     *
442
     * @param $data
443
     */
444 13
    private function createRootObjects($data)
445
    {
446 13
        if ($this->isCollection($data)) {
447 6
            $this->setRootObjects($data['data']);
448 6
        } else {
449 7
            $this->setRootObjects([$data['data']]);
450
        }
451 13
    }
452
453
454
    /**
455
     * Loops over the relationships of the provided data and formats it
456
     *
457
     * @param $data
458
     * @param $relationship
459
     * @param $nestedDepth
460
     *
461
     * @return array
462
     */
463 7
    private function fillRelationshipAsCollection($data, $relationship, $nestedDepth)
464
    {
465 7
        foreach ($relationship as $index => $relationshipData) {
466 7
            $data['data'][$index]['relationships'][$nestedDepth] = $relationshipData;
467 7
        }
468
469 7
        return $data;
470
    }
471
472
473
    /**
474
     * @param $data
475
     * @param $relationship
476
     * @param $key
477
     *
478
     * @return array
479
     */
480 10
    private function FillRelationshipAsSingleResource($data, $relationship, $key)
481
    {
482 10
        $data['data']['relationships'][$key] = $relationship[0];
483
484 10
        if ($this->shouldIncludeLinks()) {
485 2
            $data['data']['relationships'][$key] = array_merge([
486
                'links' => [
487 2
                    'self' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/relationships/$key",
488 2
                    'related' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/$key",
489 2
                ],
490 2
            ], $data['data']['relationships'][$key]);
491
492 2
            return $data;
493
        }
494 8
        return $data;
495
    }
496
497
    /**
498
     * @param $includeKey
499
     * @param $relationships
500
     * @param $includeObject
501
     * @param $key
502
     *
503
     * @return array
504
     */
505 15
    private function buildRelationships($includeKey, $relationships, $includeObject, $key)
506
    {
507 15
        $relationships = $this->addIncludekeyToRelationsIfNotSet($includeKey, $relationships);
508
509 15
        if ($this->isNull($includeObject)) {
510 2
            $relationship = $this->null();
511 15
        } elseif ($this->isEmpty($includeObject)) {
512
            $relationship = [
513 2
                'data' => [],
514 2
            ];
515 14
        } elseif ($this->isCollection($includeObject)) {
516 7
            $relationship = ['data' => []];
517
518 7
            $relationship = $this->addIncludedDataToRelationship($includeObject, $relationship);
519 7
        } else {
520
            $relationship = [
521
                'data' => [
522 9
                    'type' => $includeObject['data']['type'],
523 9
                    'id' => $includeObject['data']['id'],
524 9
                ],
525 9
            ];
526
        }
527
528 15
        $relationships[$includeKey][$key] = $relationship;
529
530 15
        return $relationships;
531
    }
532
533
    /**
534
     * @param $includeKey
535
     * @param $relationships
536
     *
537
     * @return array
538
     */
539 15
    private function addIncludekeyToRelationsIfNotSet($includeKey, $relationships)
540
    {
541 15
        if (!array_key_exists($includeKey, $relationships)) {
542 15
            $relationships[$includeKey] = [];
543 15
            return $relationships;
544
        }
545
546 7
        return $relationships;
547
    }
548
549
    /**
550
     * @param $includeObject
551
     * @param $relationship
552
     *
553
     * @return array
554
     */
555 7
    private function addIncludedDataToRelationship($includeObject, $relationship)
556
    {
557 7
        foreach ($includeObject['data'] as $object) {
558 7
            $relationship['data'][] = [
559 7
                'type' => $object['type'],
560 7
                'id' => $object['id'],
561
            ];
562 7
        }
563
564 7
        return $relationship;
565
    }
566
}
567