EmbedOneFieldDenormalizer::denormalizeField()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 4
eloc 9
c 2
b 0
f 2
nc 4
nop 5
dl 0
loc 24
ccs 8
cts 8
cp 1
crap 4
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Deserialization\Denormalizer\Relation;
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 EmbedOneFieldDenormalizer implements FieldDenormalizerInterface
15
{
16
    /**
17
     * @var string
18
     */
19
    private $class;
20
21
    /**
22
     * @var AccessorInterface
23
     */
24
    private $accessor;
25
26
    /**
27
     * @param string $class
28
     */
29
    public function __construct($class, AccessorInterface $accessor)
30 5
    {
31
        $this->class = $class;
32 5
        $this->accessor = $accessor;
33 5
    }
34 5
35
    /**
36
     * @param object $object
37
     * @param mixed  $value
38
     *
39
     * @throws DeserializerLogicException
40
     * @throws DeserializerRuntimeException
41
     */
42
    public function denormalizeField(
43
        string $path,
44
        $object,
45
        $value,
46 5
        DenormalizerContextInterface $context,
47
        DenormalizerInterface $denormalizer = null
48
    ): void {
49
        if (null === $value) {
50
            $this->accessor->setValue($object, $value);
51
52
            return;
53 5
        }
54 1
55
        if (null === $denormalizer) {
56 1
            throw DeserializerLogicException::createMissingDenormalizer($path);
57
        }
58
59 4
        if (!is_array($value)) {
60 1
            throw DeserializerRuntimeException::createInvalidDataType($path, gettype($value), 'array');
61
        }
62
63 3
        $relatedObject = $this->accessor->getValue($object) ?? $this->class;
64 1
65
        $this->accessor->setValue($object, $denormalizer->denormalize($relatedObject, $value, $context, $path));
66
    }
67
}
68