Completed
Push — master ( b761e1...8bbc83 )
by Dominik
02:21
created

ReferenceFieldDenormalizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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