ReferenceOneFieldDenormalizer::denormalizeField()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 4
Bugs 3 Features 2
Metric Value
cc 5
eloc 10
c 4
b 3
f 2
nc 4
nop 5
dl 0
loc 26
ccs 7
cts 7
cp 1
crap 5
rs 9.6111
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\DeserializerRuntimeException;
12
13
final class ReferenceOneFieldDenormalizer implements FieldDenormalizerInterface
14
{
15
    /**
16
     * @var callable
17
     */
18
    private $repository;
19
20
    /**
21
     * @var AccessorInterface
22
     */
23
    private $accessor;
24
25
    /**
26
     * @var bool
27
     */
28
    private $emptyToNull;
29
30
    public function __construct(callable $repository, AccessorInterface $accessor, bool $emptyToNull = false)
31
    {
32
        $this->repository = $repository;
33
        $this->accessor = $accessor;
34
        $this->emptyToNull = $emptyToNull;
35 6
    }
36
37 6
    /**
38 6
     * @param object $object
39 6
     * @param mixed  $value
40 6
     *
41
     * @throws DeserializerRuntimeException
42
     */
43
    public function denormalizeField(
44
        string $path,
45
        $object,
46
        $value,
47
        DenormalizerContextInterface $context,
48
        DenormalizerInterface $denormalizer = null
49
    ): void {
50
        if ('' === $value && $this->emptyToNull) {
51 6
            $this->accessor->setValue($object, null);
52
53
            return;
54
        }
55
56
        if (null === $value) {
57
            $this->accessor->setValue($object, null);
58 6
59 1
            return;
60
        }
61 1
62
        if (!is_string($value)) {
63
            throw DeserializerRuntimeException::createInvalidDataType($path, gettype($value), 'string');
64 5
        }
65 1
66
        $repository = $this->repository;
67 1
68
        $this->accessor->setValue($object, $repository($value) ?? $value);
69
    }
70
}
71