Completed
Push — master ( 0be8e1...585ca2 )
by Daniel
59:26 queued 46:02
created

ApiNormalizer::getFileData()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 50
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 4
nop 1
dl 0
loc 50
ccs 21
cts 21
cp 1
crap 6
rs 8.9777
c 0
b 0
f 0
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Serializer;
4
5
use Silverback\ApiComponentBundle\DataModifier\DataModifierInterface;
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|DataModifierInterface[] */
12
    private $normalizerMiddleware;
13
    /** @var iterable|NormalizerInterface[] */
14
    private $normalizers;
15
    /** @var DataModifierInterface[] */
16
    private $supportedModifiers = [];
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|string $format
28
     * @return bool
29
     */
30
    public function supportsNormalization($data, $format = null): bool
31
    {
32
        if (!\is_object($data)) {
33
            return false;
34
        }
35
36
        $this->supportedModifiers = [];
37
        foreach ($this->normalizerMiddleware as $modifier) {
38
            if ($modifier->supportsData($data)) {
39
                $this->supportedModifiers[] = $modifier;
40
            }
41
        }
42
43
        return !empty($this->supportedModifiers);
44
    }
45
46
    /**
47
     * Here we need to call our own entity normalizer followed by the next supported normalizer
48
     * @param mixed $object
49
     * @param null|string $format
50
     * @param array $context
51
     * @return array|bool|float|int|mixed|string
52
     */
53
    public function normalize($object, $format = null, array $context = array())
54
    {
55
        foreach ($this->supportedModifiers as $modifier) {
56
            $modifier->process($object, $context, $format);
57
        }
58
59
        foreach ($this->normalizers as $normalizer) {
60
            if ($normalizer instanceof self || !$normalizer instanceof NormalizerInterface) {
61
                continue;
62
            }
63
            if ($normalizer->supportsNormalization($object, $format)) {
64
                return $normalizer->normalize($object, $format, $context);
65
            }
66
        }
67
68
        return $object;
69
    }
70
71
    /**
72
     * @return bool
73
     */
74
    public function hasCacheableSupportsMethod(): bool
75
    {
76
        return false;
77
    }
78
}
79