Passed
Push — master ( 5278ee...479027 )
by Dominik
02:09
created

CollectionFieldDenormalizer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 67
ccs 0
cts 21
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B denormalizeField() 0 36 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
    public function __construct(string $class, AccessorInterface $accessor)
28
    {
29
        $this->class = $class;
30
        $this->accessor = $accessor;
31
    }
32
33
    /**
34
     * @param string                       $path
35
     * @param object                       $object
36
     * @param mixed                        $value
37
     * @param DenormalizerContextInterface $context
38
     * @param DenormalizerInterface|null   $denormalizer
39
     * @throws DeserializerRuntimeException
40
     */
41
    public function denormalizeField(
42
        string $path,
43
        $object,
44
        $value,
45
        DenormalizerContextInterface $context,
46
        DenormalizerInterface $denormalizer = null
47
    ) {
48
        if (null === $denormalizer) {
49
            throw DeserializerLogicException::createMissingDenormalizer($path);
50
        }
51
52
        if (!is_array($value)) {
53
            throw DeserializerRuntimeException::createInvalidType($path, 'array');
54
        }
55
56
        $existingChildObjects = $this->accessor->getValue($object) ?? [];
57
58
        $newChildObjects = [];
59
        foreach ($value as $i => $subValue) {
60
            $subPath = $path . '[' . $i . ']';
61
62
            if (!is_array($subValue)) {
63
                throw DeserializerRuntimeException::createInvalidType($subPath, 'object');
64
            }
65
66
            if (isset($existingChildObjects[$i])) {
67
                $newChildObject = $existingChildObjects[$i];
68
            } else {
69
                $newChildObject = $this->class;
70
            }
71
72
            $newChildObjects[$i] = $denormalizer->denormalize($newChildObject, $subValue, $context, $subPath);
73
        }
74
75
        $this->accessor->setValue($object, $newChildObjects);
76
    }
77
}
78