Test Failed
Push — master ( 8a2b60...8e4848 )
by Dominik
03:00
created

CollectionFieldNormalizer::normalizeField()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 12
nc 3
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Normalizer;
6
7
use Chubbyphp\Serialization\Accessor\AccessorInterface;
8
use Chubbyphp\Serialization\SerializerLogicException;
9
10
final class CollectionFieldNormalizer implements FieldNormalizerInterface
11
{
12
    /**
13
     * @var string
14
     */
15
    private $class;
16
17
    /**
18
     * @var AccessorInterface
19
     */
20
    private $accessor;
21
22
    /**
23
     * @param string            $class
24
     * @param AccessorInterface $accessor
25
     */
26
    public function __construct(string $class, AccessorInterface $accessor)
27
    {
28
        $this->class = $class;
29
        $this->accessor = $accessor;
30
    }
31
32
    /**
33
     * @param string                     $path
34
     * @param object                     $object
35
     * @param NormalizerContextInterface $context
36
     * @param NormalizerInterface|null   $normalizer
37
     *
38
     * @return mixed
39
     *
40
     * @throws SerializerLogicException
41
     */
42
    public function normalizeField(
43
        string $path,
44
        $object,
45
        NormalizerContextInterface $context,
46
        NormalizerInterface $normalizer = null
47
    ) {
48
        if (null === $normalizer) {
49
            throw SerializerLogicException::createMissingNormalizer($path);
50
        }
51
52
        $data = [];
53
        foreach ($this->accessor->getValue($object) as $i => $childObject) {
54
            $subPath = $path.'['.$i.']';
55
            $data[$i] = $normalizer->normalize($childObject, $context, $subPath);
56
        }
57
58
        return $data;
59
    }
60
}
61