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\Action\ActionCollection; |
17
|
|
|
use FiveLab\Component\Resource\Resource\Relation\RelationCollection; |
18
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; |
19
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; |
20
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Normalizer for normalize relation collection for HATEOAS. |
24
|
|
|
* |
25
|
|
|
* @author Vitaliy Zhuk <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
class RelationCollectionObjectNormalizer implements NormalizerInterface, NormalizerAwareInterface |
28
|
|
|
{ |
29
|
|
|
use NormalizerAwareTrait; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
* |
34
|
|
|
* @param RelationCollection $object |
35
|
|
|
* |
36
|
|
|
* @throws \InvalidArgumentException |
37
|
|
|
*/ |
38
|
3 |
|
public function normalize($object, $format = null, array $context = []): array |
39
|
|
|
{ |
40
|
3 |
View Code Duplication |
if (!$object instanceof RelationCollection && !$object instanceof ActionCollection) { |
|
|
|
|
41
|
1 |
|
throw new \InvalidArgumentException(\sprintf( |
42
|
1 |
|
'The normalizer support only "%s" or "%s" but "%s" given.', |
43
|
1 |
|
RelationCollection::class, |
44
|
1 |
|
ActionCollection::class, |
45
|
1 |
|
\is_object($object) ? \get_class($object) : \gettype($object) |
46
|
|
|
)); |
47
|
|
|
} |
48
|
|
|
|
49
|
2 |
|
$data = []; |
50
|
|
|
|
51
|
2 |
|
foreach ($object as $relation) { |
52
|
2 |
|
$data[$relation->getName()] = $this->normalizer->normalize($relation, $format); |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
return $data; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
3 |
|
public function supportsNormalization($data, $format = null): bool |
62
|
|
|
{ |
63
|
3 |
|
return \is_object($data) && ($data instanceof RelationCollection || $data instanceof ActionCollection); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
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.