-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathArrayBasedDeformatter.php
More file actions
333 lines (283 loc) · 12.9 KB
/
ArrayBasedDeformatter.php
File metadata and controls
333 lines (283 loc) · 12.9 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
declare(strict_types=1);
namespace Crell\Serde\Formatter;
use Crell\Serde\Attributes\Field;
use Crell\Serde\Attributes\SequenceField;
use Crell\Serde\Deserializer;
use Crell\Serde\FormatParseError;
use Crell\Serde\DeformatterResult;
use Crell\Serde\TypeCategory;
use Crell\Serde\TypeMismatch;
use Crell\Serde\ValueType;
use function Crell\fp\first;
use function Crell\fp\pipe;
use function Crell\fp\reduceWithKeys;
/**
* Utility implementations for array-based formats.
*
* Formats that work by first converting the serialized format to/from an
* array can use this trait to handle creating the array bits, then
* implement the initialize/finalize logic specific for that format.
*/
trait ArrayBasedDeformatter
{
public function deserializeInt(mixed $decoded, Field $field): int|DeformatterResult|null
{
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
$value = $decoded[$field->serializedName];
if ($field->strict) {
if (!is_int($value) && !($field->nullable && is_null($value))) {
throw TypeMismatch::create($field->serializedName, 'int', \get_debug_type($decoded[$field->serializedName]));
}
return $decoded[$field->serializedName];
}
// Weak mode.
return (int)($decoded[$field->serializedName]);
}
public function deserializeFloat(mixed $decoded, Field $field): float|DeformatterResult|null
{
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
$value = $decoded[$field->serializedName];
if ($field->strict) {
if (!is_int($value) && !is_float($value) && !($field->nullable && is_null($value))) {
throw TypeMismatch::create($field->serializedName, 'float', \get_debug_type($decoded[$field->serializedName]));
}
return $decoded[$field->serializedName];
}
// Weak mode.
return (float)($decoded[$field->serializedName]);
}
public function deserializeBool(mixed $decoded, Field $field): bool|DeformatterResult|null
{
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
$value = $decoded[$field->serializedName];
if ($field->strict) {
if (!is_bool($value) && !($field->nullable && is_null($value))) {
throw TypeMismatch::create($field->serializedName, 'bool', \get_debug_type($decoded[$field->serializedName]));
}
return $decoded[$field->serializedName];
}
// Weak mode.
return (bool)($decoded[$field->serializedName]);
}
public function deserializeString(mixed $decoded, Field $field): string|DeformatterResult|null
{
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
$value = $decoded[$field->serializedName];
if ($field->strict) {
if (!is_string($value) && !($field->nullable && is_null($value))) {
throw TypeMismatch::create($field->serializedName, 'string', \get_debug_type($value));
}
return $value;
}
// Weak mode.
return (string)($value);
}
public function deserializeNull(mixed $decoded, Field $field): ?DeformatterResult
{
// isset() returns false for null, so we cannot use that. Thanks, PHP.
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
// Strict and weak mode are the same here; null must always be null.
if (!is_null($decoded[$field->serializedName])) {
throw TypeMismatch::create($field->serializedName, 'null', \get_debug_type($decoded[$field->serializedName]));
}
return $decoded[$field->serializedName];
}
public function deserializeSequence(mixed $decoded, Field $field, Deserializer $deserializer): array|DeformatterResult|null
{
// isset() returns false for null, so we cannot use that. Thanks, PHP.
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
if ($decoded[$field->serializedName] === null) {
return null;
}
$data = $decoded[$field->serializedName];
if (!is_array($data)) {
throw TypeMismatch::create($field->serializedName, 'array (sequence)', \get_debug_type($decoded[$field->serializedName]));
}
if (!array_is_list($data)) {
if ($field->strict) {
throw TypeMismatch::create($field->serializedName, 'array (sequence)', 'associative array');
}
$data = array_values($data);
}
// This line is fine, because if typeField is somehow not of a type with an
// arrayType property, it resolves to null anyway, which is exactly what we want.
// @phpstan-ignore-next-line
$class = $field?->typeField?->arrayType ?? '';
if ($class instanceof ValueType) {
if (!$field->strict) {
$data = $class->coerce($data);
}
if ($class->assert($data)) {
return $data;
} else {
throw TypeMismatch::create($field->serializedName, "array($class->name)", "array(" . \get_debug_type($data[0]) . ')');
}
}
else if (class_exists($class) || interface_exists($class)) {
return $this->upcastArray($data, $deserializer, $class);
} else {
return $this->upcastArray($data, $deserializer);
}
}
public function deserializeDictionary(mixed $decoded, Field $field, Deserializer $deserializer): array|DeformatterResult|null
{
// isset() returns false for null, so we cannot use that. Thanks, PHP.
if (!array_key_exists($field->serializedName, $decoded)) {
return DeformatterResult::Missing;
}
if ($decoded[$field->serializedName] === null) {
return null;
}
if (!is_array($decoded[$field->serializedName])) {
throw FormatParseError::create($field, $this->format(), $decoded);
}
$data = $decoded[$field->serializedName];
// This line is fine, because if typeField is somehow not of a type with an
// arrayType property, it resolves to null anyway, which is exactly what we want.
// @phpstan-ignore-next-line
$class = $field?->typeField?->arrayType ?? '';
if ($class instanceof ValueType) {
if (!$field->strict) {
$data = $class->coerce($data);
}
if ($class->assert($data)) {
return $data;
} else {
throw TypeMismatch::create($field->serializedName, "array($class->name)", "array(" . \get_debug_type($data[array_key_first($data)] . ')'));
}
}
else if (class_exists($class) || interface_exists($class)) {
return $this->upcastArray($data, $deserializer, $class);
} else {
return $this->upcastArray($data, $deserializer);
}
}
/**
* Deserializes all elements of an array, through the recursor.
*
* @param array<int|string, mixed> $data
* @param Deserializer $deserializer
* @param string|null $type
* @return array<string|int, mixed>
*/
protected function upcastArray(array $data, Deserializer $deserializer, ?string $type = null): array
{
$upcast = function(array $ret, mixed $v, int|string $k) use ($deserializer, $type, $data) {
$map = $type ? $deserializer->typeMapper->typeMapForClass($type) : null;
$arrayType = $map?->findClass($v[$map->keyField()]) ?? $type ?? get_debug_type($v);
$f = Field::create(serializedName: "$k", phpType: $arrayType);
$ret[$k] = $deserializer->deserialize($data, $f);
return $ret;
};
return reduceWithKeys([], $upcast)($data);
}
/**
* @param array<string, mixed> $decoded
* @param Field $field
* @param Deserializer $deserializer
* @return array<string, mixed>|DeformatterResult
*/
public function deserializeObject(mixed $decoded, Field $field, Deserializer $deserializer): array|DeformatterResult|null
{
$candidateNames = [$field->serializedName, ...$field->alias];
$key = pipe($candidateNames,
first(static fn (string $name): bool => isset($decoded[$name]))
);
if (!array_key_exists($key, $decoded)) {
return DeformatterResult::Missing;
}
if (!is_array($decoded[$key])) {
throw FormatParseError::create($field, $this->format(), $decoded);
}
$data = $decoded[$key];
// Now that we have an array of the raw data, some values need to be
// recursively upcast to objects themselves, based on the information
// in the object metadata for the target object.
$usedNames = [];
$collectingArray = null;
/** @var Field[] $collectingObjects */
$collectingObjects = [];
$ret = [];
/** @var Field $propField */
foreach ($deserializer->typeMapper->propertyList($field, $data) as $propField) {
$usedNames[] = $propField->serializedName;
if ($propField->flatten && $propField->typeCategory === TypeCategory::Array) {
$collectingArray = $propField;
} elseif ($propField->flatten && $propField->typeCategory === TypeCategory::Object) {
$collectingObjects[] = $propField;
} elseif (array_key_exists($propField->serializedName, $data)) {
$ret[$propField->serializedName] = $deserializer->deserialize($data, $propField);
} else {
$key = pipe(
$propField->alias,
first(fn(string $name): bool => array_key_exists($name, $data)),
);
$ret[$propField->serializedName] = $key
? $deserializer->deserialize($data, $propField->with(serializedName: $key))
: DeformatterResult::Missing;
}
}
// Any other values are for a collecting field, if any,
// but may need to be upcast themselves.
// First upcast any values that will become properties of a collecting object.
$remaining = $this->getRemainingData($data, $usedNames);
foreach ($collectingObjects as $collectingField) {
$remaining = $this->getRemainingData($remaining, $usedNames);
$nestedProps = $deserializer->typeMapper->propertyList($collectingField, $remaining);
foreach ($nestedProps as $propField) {
// All values need to be sent through the full pipeline, even primitive ones,
// so that their types can be treated the same as non-collected properties.
$ret[$propField->serializedName] = $deserializer->deserialize($data, $propField);
$usedNames[] = $propField->serializedName;
}
}
// Then IF the remaining data is going to be collected to an array,
// and that array has a type map, upcast all elements of that array to
// the appropriate type.
$remaining = $this->getRemainingData($remaining, $usedNames);
if ($collectingArray && $map = $deserializer->typeMapper->typeMapForField($collectingArray)) {
foreach ($remaining as $k => $v) {
$class = $map->findClass($v[$map->keyField()]);
$ret[$k] = $deserializer->deserialize($remaining, Field::create(serializedName: "$k", phpType: $class));
}
} elseif ($class = $collectingArray->typeField->arrayType ?? false) {
// @todo This check should really rely on there being an interface with an arrayType
// property, which SequenceField and DictionaryField then implement. As is,
// it's a little shaky as we're just relying on both attributes having the same
// property name by convention. Something for the inevitable PHP 8.4+ upgrade.
foreach ($remaining as $k => $v) {
$ret[$k] = $deserializer->deserialize($remaining, Field::create(serializedName: "$k", phpType: $class));
}
} elseif ($remaining) {
// Otherwise, just tack on whatever is left to the processed data.
$ret = [...$ret, ...$remaining];
}
return $ret;
}
/**
* @param mixed $source
* @param string[] $used
* @return array<string, mixed>
*/
public function getRemainingData(mixed $source, array $used): array
{
return array_diff_key($source, array_flip($used));
}
public function getType(mixed $decoded, Field $field): string
{
return \get_debug_type($decoded[$field->serializedName]);
}
}