-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSerializableNormalizer.php
231 lines (206 loc) · 7.65 KB
/
SerializableNormalizer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
<?php declare(strict_types = 1);
namespace LastDragon_ru\LaraASP\Serializer\Normalizers;
use ArrayObject;
use LastDragon_ru\LaraASP\Serializer\Contracts\Partial;
use LastDragon_ru\LaraASP\Serializer\Contracts\Serializable;
use LastDragon_ru\LaraASP\Serializer\Exceptions\PartialUnserializable;
use LastDragon_ru\LaraASP\Serializer\Metadata\MetadataFactory;
use Override;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use function array_fill_keys;
use function array_map;
use function array_unshift;
use function class_exists;
use function is_a;
use function is_array;
use function is_object;
use function is_string;
/**
* Special serializer for {@see Serializable}.
*
* Only public properties will be serialized. Accessors/mutators/magic/etc
* doesn't supported. If you need it, please consider using one of Symfony's
* normalizer like {@see ObjectNormalizer}.
*
* @see SerializableNormalizerContextBuilder
* @see ObjectNormalizer
* @see MetadataFactory
*/
class SerializableNormalizer extends AbstractObjectNormalizer {
/**
* @var array<string, array<string, true>>
*/
private array $attributes = [];
/**
* @var array<string, string>
*/
private array $discriminators = [];
/**
* @param array<string, mixed> $defaultContext
*/
public function __construct(
MetadataFactory $metadata,
array $defaultContext = [],
) {
if (!class_exists(PropertyAccess::class)) {
/**
* The class is required for {@see AbstractObjectNormalizer}. We
* need to add the package to our 'composer.json' since
* `symfony/serializer` doesn't require it directly. But it
* will lead to "unused package error" during CI checks. So the
* condition needs only for CI :)
*/
}
parent::__construct(
classMetadataFactory : $metadata,
nameConverter : new MetadataAwareNameConverter($metadata),
propertyTypeExtractor: $metadata,
defaultContext : $defaultContext,
);
}
/**
* @return array<class-string, bool>
*/
#[Override]
public function getSupportedTypes(?string $format): array {
return [
Serializable::class => self::class === static::class,
];
}
/**
* @param array<array-key, mixed> $context
*/
#[Override]
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed {
$class = $this->getTypeClass($type, $data);
if (is_a($class, Partial::class, true)) {
$context[AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES] = true;
}
return parent::denormalize($data, $class, $format, $context);
}
/**
* @param array<array-key, mixed> $context
*
* @return array<array-key, mixed>|string|int|float|bool|ArrayObject<array-key, mixed>|null
*/
#[Override]
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array|string|int|float|bool|ArrayObject|null {
if ($object instanceof Partial || (is_string($object) && is_a($object, Partial::class, true))) {
throw new PartialUnserializable();
}
return parent::normalize($object, $format, $context);
}
/**
* @param array<array-key, mixed> $context
*/
#[Override]
protected function getAllowedAttributes(
object|string $classOrObject,
array $context,
bool $attributesAsString = false,
): array|bool {
$attributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
if (is_array($attributes)) {
$class = is_object($classOrObject) ? $classOrObject::class : $classOrObject;
$mapping = $this->classDiscriminatorResolver?->getMappingForMappedObject($classOrObject);
$properties = array_map(
static function (mixed $attribute): string {
return is_object($attribute) ? $attribute->getName() : $attribute;
},
$attributes,
);
$this->attributes[$class] = array_fill_keys($properties, true);
if ($mapping !== null) {
$property = $mapping->getTypeProperty();
$this->discriminators[$class] = $property;
if (!isset($this->attributes[$class][$property])) {
array_unshift($attributes, $attributesAsString ? $property : new AttributeMetadata($property));
}
}
}
return $attributes;
}
/**
* @param array<array-key, mixed> $context
*
* @return array<array-key, string>
*/
#[Override]
protected function extractAttributes(object $object, ?string $format = null, array $context = []): array {
return [
/**
* The method is never called because the {@see static::$classMetadataFactory} is always defined.
*/
];
}
/**
* @param array<array-key, mixed> $context
*/
#[Override]
protected function getAttributeValue(
object $object,
string $attribute,
?string $format = null,
array $context = [],
): mixed {
return $this->isDiscriminator($object::class, $attribute)
? $this->classDiscriminatorResolver?->getTypeForMappedObject($object)
: $object->{$attribute};
}
/**
* @param array<array-key, mixed> $context
*/
#[Override]
protected function setAttributeValue(
object $object,
string $attribute,
mixed $value,
?string $format = null,
array $context = [],
): void {
if ($this->isAttribute($object::class, $attribute)) {
$object->{$attribute} = $value;
}
}
/**
* @param class-string $class
*/
private function isDiscriminator(string $class, string $attribute): bool {
return ($this->discriminators[$class] ?? null) === $attribute;
}
/**
* @param class-string $class
*/
private function isAttribute(string $class, string $attribute): bool {
return $this->attributes[$class][$attribute] ?? false;
}
/**
* I'm not sure if it is bug or not, but out the box symfony call
* {@see AbstractObjectNormalizer::getMappedClass()} after the
* {@see AbstractObjectNormalizer::getAllowedAttributes()}. So it uses
* an invalid set of allowed attributes. It may lead to "extra property"
* error while deserialization of abstract classes/interfaces. To avoid
* it, the {@see ObjectNormalizer} adds all properties from all known
* classes into the array of allowed properties. It looks strange...
*
* This is why we are trying to replace the `$type` into actual class
* before deserialization.
*/
private function getTypeClass(string $type, mixed $data): string {
$mapping = $this->classDiscriminatorResolver?->getMappingForClass($type);
$property = $mapping?->getTypeProperty();
$class = $property !== null && is_array($data) && isset($data[$property]) && is_string($data[$property])
? $mapping?->getClassForType($data[$property])
: null;
return $class ?? $type;
}
}