Passed
Pull Request — master (#7)
by Dominik
03:31
created

ReferenceManyFieldDenormalizer::denormalizeField()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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