Passed
Push — master ( 794775...6d18bb )
by Dominik
02:17
created

ReferenceOneFieldDenormalizer::denormalizeField()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 9
cts 9
cp 1
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 13
nc 3
nop 5
crap 3
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
     * @param callable          $repository
27
     * @param AccessorInterface $accessor
28
     */
29 3
    public function __construct(callable $repository, AccessorInterface $accessor)
30
    {
31 3
        $this->repository = $repository;
32 3
        $this->accessor = $accessor;
33 3
    }
34
35
    /**
36
     * @param string                       $path
37
     * @param object                       $object
38
     * @param mixed                        $value
39
     * @param DenormalizerContextInterface $context
40
     * @param DenormalizerInterface|null   $denormalizer
41
     *
42
     * @throws DeserializerRuntimeException
43
     */
44 3
    public function denormalizeField(
45
        string $path,
46
        $object,
47
        $value,
48
        DenormalizerContextInterface $context,
49
        DenormalizerInterface $denormalizer = null
50
    ) {
51 3
        if (null === $value) {
52 1
            $this->accessor->setValue($object, $value);
53
54 1
            return;
55
        }
56
57 2
        if (!is_string($value)) {
58 1
            throw DeserializerRuntimeException::createInvalidDataType($path, gettype($value), 'string');
59
        }
60
61 1
        $repository = $this->repository;
62
63 1
        $this->accessor->setValue($object, $repository($value));
64 1
    }
65
}
66