|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Serializer\Normalizer; |
|
4
|
|
|
|
|
5
|
|
|
use Bdf\Serializer\Context\DenormalizationContext; |
|
6
|
|
|
use Bdf\Serializer\Context\NormalizationContext; |
|
7
|
|
|
use Bdf\Serializer\Type\Type; |
|
8
|
|
|
use Bdf\Serializer\Type\TypeFactory; |
|
9
|
|
|
use stdClass; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* ObjectNormalizer |
|
13
|
|
|
* |
|
14
|
|
|
* @author Seb |
|
15
|
|
|
* |
|
16
|
|
|
* @implements NormalizerInterface<stdClass> |
|
17
|
|
|
*/ |
|
18
|
|
|
class ObjectNormalizer implements NormalizerInterface, AutoRegisterInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* {@inheritdoc} |
|
22
|
|
|
*/ |
|
23
|
6 |
|
public function normalize($data, NormalizationContext $context) |
|
24
|
|
|
{ |
|
25
|
6 |
|
$hash = $context->assertNoCircularReference($data); |
|
26
|
|
|
|
|
27
|
6 |
|
$normalized = []; |
|
28
|
|
|
|
|
29
|
6 |
|
foreach ((array)$data as $property => $value) { |
|
30
|
6 |
|
$value = $context->root()->normalize($value, $context); |
|
31
|
|
|
|
|
32
|
4 |
|
if ($value === null && !$context->shouldAddNull()) { |
|
33
|
|
|
continue; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
4 |
|
$normalized[$property] = $value; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
4 |
|
$context->releaseReference($hash); |
|
40
|
|
|
|
|
41
|
4 |
|
return $normalized; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* {@inheritdoc} |
|
46
|
|
|
*/ |
|
47
|
4 |
|
public function denormalize($data, Type $type, DenormalizationContext $context) |
|
48
|
|
|
{ |
|
49
|
4 |
|
$object = $this->instantiate($type); |
|
50
|
|
|
|
|
51
|
4 |
|
foreach ((array)$data as $name => $propertyData) { |
|
52
|
4 |
|
$object->$name = $context->root()->denormalize($propertyData, TypeFactory::mixedType(), $context); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
4 |
|
return $object; |
|
|
|
|
|
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Instanciate an object |
|
60
|
|
|
* |
|
61
|
|
|
* @param Type $type |
|
62
|
|
|
* |
|
63
|
|
|
* @return stdClass |
|
64
|
|
|
*/ |
|
65
|
4 |
|
private function instantiate($type) |
|
66
|
|
|
{ |
|
67
|
4 |
|
return $type->target() ?: new stdClass(); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* {@inheritdoc} |
|
72
|
|
|
*/ |
|
73
|
2 |
|
public function supports(string $className): bool |
|
74
|
|
|
{ |
|
75
|
2 |
|
return $className === stdClass::class; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* {@inheritdoc} |
|
80
|
|
|
*/ |
|
81
|
12 |
|
public function registerTo(NormalizerLoaderInterface $loader): void |
|
82
|
|
|
{ |
|
83
|
12 |
|
$loader->associate(stdClass::class, $this); |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: