ReferenceOneFieldDenormalizer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 4 Features 2
Metric Value
eloc 17
c 5
b 4
f 2
dl 0
loc 56
ccs 12
cts 12
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A denormalizeField() 0 26 5
A __construct() 0 5 1
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