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\ActionInterface; |
17
|
|
|
use FiveLab\Component\Resource\Resource\Relation\RelationInterface; |
18
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Normalizer for normalize relation object for HATEOAS. |
22
|
|
|
* |
23
|
|
|
* @author Vitaliy Zhuk <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
class RelationObjectNormalizer implements NormalizerInterface |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* {@inheritdoc} |
29
|
|
|
* |
30
|
|
|
* @throws \InvalidArgumentException |
31
|
|
|
*/ |
32
|
3 |
|
public function normalize($object, $format = null, array $context = []): array |
33
|
|
|
{ |
34
|
3 |
View Code Duplication |
if (!$object instanceof RelationInterface && !$object instanceof ActionInterface) { |
|
|
|
|
35
|
1 |
|
throw new \InvalidArgumentException(\sprintf( |
36
|
1 |
|
'The normalizer support only "%s" or "%s" but "%s" given.', |
37
|
1 |
|
RelationInterface::class, |
38
|
1 |
|
ActionInterface::class, |
39
|
1 |
|
\is_object($object) ? \get_class($object) : \gettype($object) |
40
|
|
|
)); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$data = [ |
44
|
2 |
|
'href' => $object->getHref()->getPath(), |
45
|
|
|
]; |
46
|
|
|
|
47
|
2 |
|
if ($object->getHref()->isTemplated()) { |
48
|
2 |
|
$data['templated'] = true; |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
if (count($object->getAttributes())) { |
52
|
2 |
|
$data['attributes'] = $object->getAttributes(); |
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 RelationInterface || $data instanceof ActionInterface); |
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.