Completed
Pull Request — master (#325)
by
unknown
03:24
created

JsonApiSerializer::shouldIncludeLinks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
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 35
    public function __construct($baseUrl = null)
29
    {
30 35
        $this->baseUrl = $baseUrl;
31 35
        $this->rootObjects = [];
32 35
    }
33
34
    /**
35
     * Serialize a collection.
36
     *
37
     * @param string $resourceKey
38
     * @param array $data
39
     *
40
     * @return array
41
     */
42 19
    public function collection($resourceKey, array $data)
43
    {
44 19
        $resources = [];
45
46 19
        foreach ($data as $resource) {
47 18
            $resources[] = $this->item($resourceKey, $resource)['data'];
48 19
        }
49
50 19
        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 35
    public function item($resourceKey, array $data)
62
    {
63 35
        $id = $this->getIdFromData($data);
64
65
        $resource = [
66
            'data' => [
67 32
                'type' => $resourceKey,
68 32
                'id' => "$id",
69 32
                'attributes' => $data,
70 32
            ],
71 32
        ];
72
73 32
        unset($resource['data']['attributes']['id']);
74
75 32
        if(isset($resource['data']['attributes']['links'])) {
76 1
            $custom_links = $data['links'];
77 1
            unset($resource['data']['attributes']['links']);
78 1
        }
79
80 32
        if ($this->shouldIncludeLinks()) {
81 11
            $resource['data']['links'] = [
82 11
                'self' => "{$this->baseUrl}/$resourceKey/$id",
83
            ];
84 11
            if(isset($custom_links)) {
85 1
                $resource['data']['links'] = array_merge($custom_links, $resource['data']['links']);
86 1
            }
87 11
        }
88
89 32
        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 32
    public function meta(array $meta)
138
    {
139 32
        if (empty($meta)) {
140 27
            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 32
    public function includedData(ResourceInterface $resource, array $data)
172
    {
173 32
        list($serializedData, $linkedIds) = $this->pullOutNestedIncludedData($data);
174
175 32
        foreach ($data as $value) {
176 32
            foreach ($value as $includeObject) {
177 17
                if ($this->isNull($includeObject) || $this->isEmpty($includeObject)) {
178 4
                    continue;
179
                }
180
181 15
                $includeObjects = $this->createIncludeObjects($includeObject);
182
183 15 View Code Duplication
                foreach ($includeObjects as $object) {
184 15
                    $includeType = $object['type'];
185 15
                    $includeId = $object['id'];
186 15
                    $cacheKey = "$includeType:$includeId";
187 15
                    if (!array_key_exists($cacheKey, $linkedIds)) {
188 15
                        $serializedData[] = $object;
189 15
                        $linkedIds[$cacheKey] = $object;
190 15
                    }
191 15
                }
192 32
            }
193 32
        }
194
195 32
        return empty($serializedData) ? [] : ['included' => $serializedData];
196
    }
197
198
    /**
199
     * Indicates if includes should be side-loaded.
200
     *
201
     * @return bool
202
     */
203 35
    public function sideloadIncludes()
204
    {
205 35
        return true;
206
    }
207
208
    /**
209
     * @param array $data
210
     * @param array $includedData
211
     *
212
     * @return array
213
     */
214 32
    public function injectData($data, $includedData)
215
    {
216 32
        $relationships = $this->parseRelationships($includedData);
217
218 32
        if (!empty($relationships)) {
219 17
            $data = $this->fillRelationships($data, $relationships);
220 17
        }
221
222 32
        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 32
    public function filterIncludes($includedData, $data)
238
    {
239 32
        if (!isset($includedData['included'])) {
240 17
            return $includedData;
241
        }
242
243
        // Create the RootObjects
244 15
        $this->createRootObjects($data);
245
246
        // Filter out the root objects
247 15
        $filteredIncludes = array_filter($includedData['included'], [$this, 'filterRootObject']);
248
249
        // Reset array indizes
250 15
        $includedData['included'] = array_merge([], $filteredIncludes);
251
252 15
        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 15
    protected function filterRootObject($object)
263
    {
264 15
        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 15
        $this->rootObjects = array_map(function ($object) {
275 15
            return "{$object['type']}:{$object['id']}";
276 15
        }, $objects);
277 15
    }
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 15
    protected function isRootObject($object)
287
    {
288 15
        $objectKey = "{$object['type']}:{$object['id']}";
289 15
        return in_array($objectKey, $this->rootObjects);
290
    }
291
292
    /**
293
     * @param array $data
294
     *
295
     * @return bool
296
     */
297 17
    protected function isCollection($data)
298
    {
299 17
        return array_key_exists('data', $data) &&
300 17
        array_key_exists(0, $data['data']);
301
    }
302
303
    /**
304
     * @param array $data
305
     *
306
     * @return bool
307
     */
308 17
    protected function isNull($data)
309
    {
310 17
        return array_key_exists('data', $data) && $data['data'] === null;
311
    }
312
313
    /**
314
     * @param array $data
315
     *
316
     * @return bool
317
     */
318 16
    protected function isEmpty($data)
319
    {
320 16
        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 17
    protected function fillRelationships($data, $relationships)
330
    {
331 17
        if ($this->isCollection($data)) {
332 9
            foreach ($relationships as $key => $relationship) {
333 9
                $data = $this->fillRelationshipAsCollection($data, $relationship, $key);
334 9
            }
335 9
        } else { // Single resource
336 10
            foreach ($relationships as $key => $relationship) {
337 10
                $data = $this->fillRelationshipAsSingleResource($data, $relationship, $key);
338 10
            }
339
        }
340
341 17
        return $data;
342
    }
343
344
    /**
345
     * @param array $includedData
346
     *
347
     * @return array
348
     */
349 32
    protected function parseRelationships($includedData)
350
    {
351 32
        $relationships = [];
352
353 32
        foreach ($includedData as $key => $inclusion) {
354 32
            foreach ($inclusion as $includeKey => $includeObject) {
355 17
                $relationships = $this->buildRelationships($includeKey, $relationships, $includeObject, $key);
356 32
            }
357 32
        }
358
359 32
        return $relationships;
360
    }
361
362
    /**
363
     * @param array $data
364
     *
365
     * @return integer
366
     */
367 35
    protected function getIdFromData(array $data)
368
    {
369 35
        $isASerializableObject = is_object($data['id']) && is_callable([$data['id'], '__toString']);
370 34
        if (!array_key_exists('id', $data) || !(is_scalar($data['id']) || $isASerializableObject)) {
371 2
            throw new InvalidArgumentException(
372
                'JSON API resource objects MUST have a valid id (string or possible to represent as a string)'
373 2
            );
374
        }
375 32
        return $data['id'];
376
    }
377
378
    /**
379
     * Keep all sideloaded inclusion data on the top level.
380
     *
381
     * @param array $data
382
     *
383
     * @return array
384
     */
385 32
    protected function pullOutNestedIncludedData(array $data)
386
    {
387 32
        $includedData = [];
388 32
        $linkedIds = [];
389
390 32
        foreach ($data as $value) {
391 32
            foreach ($value as $includeObject) {
392 17
                if (isset($includeObject['included'])) {
393 3 View Code Duplication
                    foreach ($includeObject['included'] as $object) {
394 3
                        $includeType = $object['type'];
395 3
                        $includeId = $object['id'];
396 3
                        $cacheKey = "$includeType:$includeId";
397
398 3
                        if (!array_key_exists($cacheKey, $linkedIds)) {
399 3
                            $includedData[] = $object;
400 3
                            $linkedIds[$cacheKey] = $object;
401 3
                        }
402 3
                    }
403 3
                }
404 32
            }
405 32
        }
406
407 32
        return [$includedData, $linkedIds];
408
    }
409
410
    /**
411
     * Whether or not the serializer should include `links` for resource objects.
412
     *
413
     * @return bool
414
     */
415 32
    protected function shouldIncludeLinks()
416
    {
417 32
        return $this->baseUrl !== null;
418
    }
419
420
    /**
421
     * Check if the objects are part of a collection or not
422
     *
423
     * @param $includeObject
424
     *
425
     * @return array
426
     */
427 15
    private function createIncludeObjects($includeObject)
428
    {
429 15
        if ($this->isCollection($includeObject)) {
430 8
            $includeObjects = $includeObject['data'];
431
432 8
            return $includeObjects;
433
        } else {
434 10
            $includeObjects = [$includeObject['data']];
435
436 10
            return $includeObjects;
437
        }
438
    }
439
440
    /**
441
     * Sets the RootObjects, either as collection or not.
442
     *
443
     * @param $data
444
     */
445 15
    private function createRootObjects($data)
446
    {
447 15
        if ($this->isCollection($data)) {
448 8
            $this->setRootObjects($data['data']);
449 8
        } else {
450 7
            $this->setRootObjects([$data['data']]);
451
        }
452 15
    }
453
454
455
    /**
456
     * Loops over the relationships of the provided data and formats it
457
     *
458
     * @param $data
459
     * @param $relationship
460
     * @param $key
461
     *
462
     * @return array
463
     */
464 9
    private function fillRelationshipAsCollection($data, $relationship, $key)
465
    {
466 9
        foreach ($relationship as $index => $relationshipData) {
467 9
            $data['data'][$index]['relationships'][$key] = $relationshipData;
468
469 9
            if ($this->shouldIncludeLinks()) {
470 2
                $data['data'][$index]['relationships'][$key] = array_merge([
471
                    'links' => [
472 2
                        'self' => "{$this->baseUrl}/{$data['data'][$index]['type']}/{$data['data'][$index]['id']}/relationships/$key",
473 2
                        'related' => "{$this->baseUrl}/{$data['data'][$index]['type']}/{$data['data'][$index]['id']}/$key",
474 2
                    ],
475 2
                ], $data['data'][$index]['relationships'][$key]);
476 2
            }
477 9
        }
478
479 9
        return $data;
480
    }
481
482
483
    /**
484
     * @param $data
485
     * @param $relationship
486
     * @param $key
487
     *
488
     * @return array
489
     */
490 10
    private function fillRelationshipAsSingleResource($data, $relationship, $key)
491
    {
492 10
        $data['data']['relationships'][$key] = $relationship[0];
493
494 10
        if ($this->shouldIncludeLinks()) {
495 2
            $data['data']['relationships'][$key] = array_merge([
496
                'links' => [
497 2
                    'self' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/relationships/$key",
498 2
                    'related' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/$key",
499 2
                ],
500 2
            ], $data['data']['relationships'][$key]);
501
502 2
            return $data;
503
        }
504 8
        return $data;
505
    }
506
507
    /**
508
     * @param $includeKey
509
     * @param $relationships
510
     * @param $includeObject
511
     * @param $key
512
     *
513
     * @return array
514
     */
515 17
    private function buildRelationships($includeKey, $relationships, $includeObject, $key)
516
    {
517 17
        $relationships = $this->addIncludekeyToRelationsIfNotSet($includeKey, $relationships);
518
519 17
        if ($this->isNull($includeObject)) {
520 2
            $relationship = $this->null();
521 17
        } elseif ($this->isEmpty($includeObject)) {
522
            $relationship = [
523 2
                'data' => [],
524 2
            ];
525 16
        } elseif ($this->isCollection($includeObject)) {
526 8
            $relationship = ['data' => []];
527
528 8
            $relationship = $this->addIncludedDataToRelationship($includeObject, $relationship);
529 8
        } else {
530
            $relationship = [
531
                'data' => [
532 10
                    'type' => $includeObject['data']['type'],
533 10
                    'id' => $includeObject['data']['id'],
534 10
                ],
535 10
            ];
536
        }
537
538 17
        $relationships[$includeKey][$key] = $relationship;
539
540 17
        return $relationships;
541
    }
542
543
    /**
544
     * @param $includeKey
545
     * @param $relationships
546
     *
547
     * @return array
548
     */
549 17
    private function addIncludekeyToRelationsIfNotSet($includeKey, $relationships)
550
    {
551 17
        if (!array_key_exists($includeKey, $relationships)) {
552 17
            $relationships[$includeKey] = [];
553 17
            return $relationships;
554
        }
555
556 9
        return $relationships;
557
    }
558
559
    /**
560
     * @param $includeObject
561
     * @param $relationship
562
     *
563
     * @return array
564
     */
565 8
    private function addIncludedDataToRelationship($includeObject, $relationship)
566
    {
567 8
        foreach ($includeObject['data'] as $object) {
568 8
            $relationship['data'][] = [
569 8
                'type' => $object['type'],
570 8
                'id' => $object['id'],
571
            ];
572 8
        }
573
574 8
        return $relationship;
575
    }
576
}
577