1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silverback\ApiComponentBundle\Serializer; |
4
|
|
|
|
5
|
|
|
use Silverback\ApiComponentBundle\Serializer\Middleware\MiddlewareInterface; |
6
|
|
|
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface; |
7
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
8
|
|
|
|
9
|
|
|
class ApiNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface |
10
|
|
|
{ |
11
|
|
|
/** @var iterable|MiddlewareInterface[] */ |
12
|
|
|
private $normalizerMiddleware; |
13
|
|
|
/** @var iterable|NormalizerInterface[] */ |
14
|
|
|
private $normalizers; |
15
|
|
|
/** @var MiddlewareInterface[] */ |
16
|
|
|
private $supportedMiddleware = []; |
17
|
|
|
|
18
|
|
|
public function __construct(iterable $normalizerMiddleware, iterable $normalizers) |
19
|
|
|
{ |
20
|
|
|
$this->normalizerMiddleware = $normalizerMiddleware; |
21
|
|
|
$this->normalizers = $normalizers; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Check if any of our entity normalizers should be called |
26
|
|
|
* @param mixed $data |
27
|
|
|
* @param null $format |
|
|
|
|
28
|
|
|
* @return bool |
29
|
|
|
*/ |
30
|
|
|
public function supportsNormalization($data, $format = null): bool |
31
|
|
|
{ |
32
|
|
|
if (!\is_object($data)) { |
33
|
|
|
return false; |
34
|
|
|
} |
35
|
|
|
$this->supportedMiddleware = []; |
36
|
|
|
foreach ($this->normalizerMiddleware as $modifier) { |
37
|
|
|
if ($modifier->supportsData($data)) { |
38
|
|
|
$this->supportedMiddleware[] = $modifier; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
return !empty($this->supportedMiddleware); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Here we need to call our own entity normalizer followed by the next supported normalizer |
46
|
|
|
* @param mixed $object |
47
|
|
|
* @param null $format |
|
|
|
|
48
|
|
|
* @param array $context |
49
|
|
|
* @return array|bool|float|int|mixed|string |
50
|
|
|
*/ |
51
|
|
|
public function normalize($object, $format = null, array $context = array()) |
52
|
|
|
{ |
53
|
|
|
foreach ($this->supportedMiddleware as $modifier) { |
54
|
|
|
$modifier->process($object); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
foreach ($this->normalizers as $normalizer) { |
58
|
|
|
if ($normalizer instanceof self) { |
59
|
|
|
continue; |
60
|
|
|
} |
61
|
|
|
if ($normalizer->supportsNormalization($object, $format)) { |
62
|
|
|
return $normalizer->normalize($object, $format, $context); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $object; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return bool |
71
|
|
|
*/ |
72
|
|
|
public function hasCacheableSupportsMethod(): bool |
73
|
|
|
{ |
74
|
|
|
return true; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|