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
|
|
|
|