Completed
Push — master ( f66c71...974ce1 )
by Dominik
01:48
created

CollectionFieldDenormalizer::denormalizeField()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 17
cts 17
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 22
nc 6
nop 5
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Deserialization\Denormalizer;
6
7
use Chubbyphp\Deserialization\Accessor\AccessorInterface;
8
use Chubbyphp\Deserialization\DeserializerLogicException;
9
use Chubbyphp\Deserialization\DeserializerRuntimeException;
10
11
final class CollectionFieldDenormalizer implements FieldDenormalizerInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    private $class;
17
18
    /**
19
     * @var AccessorInterface
20
     */
21
    private $accessor;
22
23
    /**
24
     * @param string            $class
25
     * @param AccessorInterface $accessor
26
     */
27 5
    public function __construct(string $class, AccessorInterface $accessor)
28
    {
29 5
        $this->class = $class;
30 5
        $this->accessor = $accessor;
31 5
    }
32
33
    /**
34
     * @param string                       $path
35
     * @param object                       $object
36
     * @param mixed                        $value
37
     * @param DenormalizerContextInterface $context
38
     * @param DenormalizerInterface|null   $denormalizer
39
     *
40
     * @throws DeserializerLogicException
41
     * @throws DeserializerRuntimeException
42
     */
43 5
    public function denormalizeField(
44
        string $path,
45
        $object,
46
        $value,
47
        DenormalizerContextInterface $context,
48
        DenormalizerInterface $denormalizer = null
49
    ) {
50 5
        if (null === $denormalizer) {
51 1
            throw DeserializerLogicException::createMissingDenormalizer($path);
52
        }
53
54 4
        if (!is_array($value)) {
55 1
            throw DeserializerRuntimeException::createInvalidType($path, gettype($value), 'array');
56
        }
57
58 3
        $existingChildObjects = $this->accessor->getValue($object) ?? [];
59
60 3
        $newChildObjects = [];
61 3
        foreach ($value as $i => $subValue) {
62 3
            $subPath = $path.'['.$i.']';
63
64 3
            if (!is_array($subValue)) {
65 1
                throw DeserializerRuntimeException::createInvalidType($subPath, gettype($value), 'object');
66
            }
67
68 2
            if (isset($existingChildObjects[$i])) {
69 1
                $newChildObject = $existingChildObjects[$i];
70
            } else {
71 1
                $newChildObject = $this->class;
72
            }
73
74 2
            $newChildObjects[$i] = $denormalizer->denormalize($newChildObject, $subValue, $context, $subPath);
75
        }
76
77 2
        $this->accessor->setValue($object, $newChildObjects);
78 2
    }
79
}
80