|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the FiveLab Resource package |
|
7
|
|
|
* |
|
8
|
|
|
* (c) FiveLab |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
11
|
|
|
* file that was distributed with this source code |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
namespace FiveLab\Component\Resource\Serializers\Hateoas\Normalizer; |
|
15
|
|
|
|
|
16
|
|
|
use FiveLab\Component\Resource\Resource\ResourceCollection; |
|
17
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; |
|
18
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; |
|
19
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* The normalizer for normalize resource collection. |
|
23
|
|
|
* |
|
24
|
|
|
* @author Vitaliy Zhuk <[email protected]> |
|
25
|
|
|
*/ |
|
26
|
|
|
class ResourceCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface |
|
27
|
|
|
{ |
|
28
|
|
|
use NormalizerAwareTrait; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* {@inheritdoc} |
|
32
|
|
|
* |
|
33
|
|
|
* @param ResourceCollection $object |
|
34
|
|
|
* |
|
35
|
|
|
* @throws \InvalidArgumentException |
|
36
|
|
|
*/ |
|
37
|
|
|
public function normalize($object, $format = null, array $context = []) |
|
38
|
|
|
{ |
|
39
|
|
|
$data = []; |
|
40
|
|
|
$links = []; |
|
41
|
|
|
|
|
42
|
|
|
if (\count($object->getRelations())) { |
|
43
|
|
|
// @phpstan-ignore-next-line |
|
44
|
|
|
$links = \array_merge($links, $this->normalizer->normalize($object->getRelations(), $format, $context)); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
if (\count($object->getActions())) { |
|
48
|
|
|
// @phpstan-ignore-next-line |
|
49
|
|
|
$links = \array_merge($links, $this->normalizer->normalize($object->getActions(), $format, $context)); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
foreach ($object as $resource) { |
|
53
|
|
|
$data[] = $this->normalizer->normalize($resource, $format, $context); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
if (\count($links)) { |
|
57
|
|
|
return [ |
|
58
|
|
|
'_links' => $links, |
|
59
|
|
|
'_embedded' => [ |
|
60
|
|
|
'items' => $data, |
|
61
|
|
|
], |
|
62
|
|
|
]; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return $data; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* {@inheritdoc} |
|
70
|
|
|
*/ |
|
71
|
|
|
public function supportsNormalization($data, $format = null): bool |
|
72
|
|
|
{ |
|
73
|
|
|
return \is_object($data) && $data instanceof ResourceCollection; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|