-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSerializer.php
423 lines (370 loc) · 14 KB
/
Serializer.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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
<?php
declare(strict_types=1);
namespace Mapado\RestClientSdk\Model;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;
use Mapado\RestClientSdk\Exception\MissingSetterException;
use Mapado\RestClientSdk\Exception\SdkException;
use Mapado\RestClientSdk\Helper\ArrayHelper;
use Mapado\RestClientSdk\Mapping;
use Mapado\RestClientSdk\Mapping\ClassMetadata;
use Mapado\RestClientSdk\SdkClient;
use Mapado\RestClientSdk\UnitOfWork;
use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
/**
* Class Serializer
*
* @author Julien Deniau <[email protected]>
*/
class Serializer
{
/**
* mapping
*
* @var Mapping
*/
private $mapping;
/**
* @var SdkClient
*/
private $sdk;
/**
* @var UnitOfWork
*/
private $unitOfWork;
/**
* @var PropertyAccessor
*/
private $propertyAccessor;
public function __construct(Mapping $mapping, UnitOfWork $unitOfWork)
{
$this->mapping = $mapping;
$this->unitOfWork = $unitOfWork;
$this->propertyAccessor = PropertyAccess::createPropertyAccessor();
}
/**
* @required
*/
public function setSdk(SdkClient $sdk): self
{
$this->sdk = $sdk;
return $this;
}
/**
* serialize entity for POST and PUT
*/
public function serialize(
object $entity,
string $modelName,
array $context = []
): array {
$out = $this->recursiveSerialize($entity, $modelName, 0, $context);
if (is_string($out)) {
throw new \RuntimeException(
'recursiveSerialize should return an array for level 0 of serialization. This should not happen.'
);
}
return $out;
}
/**
* @param array $data
* @param class-string $className
*/
public function deserialize(array $data, string $className): object
{
$className = $this->resolveRealClassName($data, $className);
$classMetadata = $this->mapping->getClassMetadata($className);
$attributeList = $classMetadata->getAttributeList();
$instance = new $className();
if (!is_object($instance)) {
throw new \RuntimeException(
"The class $className is not instantiable"
);
}
if ($attributeList) {
foreach ($attributeList as $attribute) {
$key = $attribute->getSerializedKey();
if (!ArrayHelper::arrayHas($data, $key)) {
continue;
}
$value = ArrayHelper::arrayGet($data, $key);
$attributeName = $attribute->getAttributeName();
$this->throwIfAttributeIsNotWritable($instance, $attributeName);
$relation = $classMetadata->getRelation($key);
if ($relation) {
if (is_string($value)) {
$value = $this->sdk->createProxy($value);
} elseif (is_array($value)) {
$targetEntity = $relation->getTargetEntity();
$relationClassMetadata = $this->mapping->getClassMetadata(
$targetEntity
);
if ($relation->isManyToOne()) {
$value = $this->deserialize(
$value,
$relationClassMetadata->getModelName()
);
} else {
// One-To-Many association
$list = [];
foreach ($value as $item) {
if (is_string($item)) {
$list[] = $this->sdk->createProxy($item);
} elseif (is_array($item)) {
$list[] = $this->deserialize(
$item,
$relationClassMetadata->getModelName()
);
}
}
$value = $list;
}
}
}
if (isset($value)) {
if ('datetime' === $attribute->getType()) {
if (!is_string($value)) {
throw new \RuntimeException(
"The value for $attributeName to cast to datetime value should be a string"
);
}
$this->setDateTimeValue(
$instance,
$attributeName,
$value
);
} else {
$this->propertyAccessor->setValue(
$instance,
$attributeName,
$value
);
}
}
}
}
$classMetadata = $this->getClassMetadata($instance);
if ($classMetadata->hasIdentifierAttribute()) {
$idGetter = $classMetadata->getIdGetter();
if ($idGetter) {
$callable = [$instance, $idGetter];
$identifier = is_callable($callable)
? call_user_func($callable)
: null;
if ($identifier) {
$this->unitOfWork->registerClean(
(string) $identifier,
$instance
);
}
}
}
return $instance;
}
/**
* If provided class name is abstract (a base class), the real class name (child class)
* may be available in some data fields.
*/
private function resolveRealClassName(
array $data,
string $className
): string {
if (!empty($data['@id'])) {
$classMetadata = $this->mapping->tryGetClassMetadataById(
$data['@id']
);
if ($classMetadata) {
return $classMetadata->getModelName();
}
}
// Real class name could also be retrieved from @type property.
return $className;
}
/**
* @return array|string
*/
private function recursiveSerialize(
object $entity,
string $modelName,
int $level = 0,
array $context = []
) {
$classMetadata = $this->mapping->getClassMetadata($modelName);
if ($level > 0 && empty($context['serializeRelation'])) {
if ($classMetadata->hasIdentifierAttribute()) {
$tmpId = $entity->{$classMetadata->getIdGetter()}();
if ($tmpId) {
return $tmpId;
}
}
}
$attributeList = $classMetadata->getAttributeList();
$out = [];
if (!empty($attributeList)) {
foreach ($attributeList as $attribute) {
$method = 'get' . ucfirst($attribute->getAttributeName());
if ($attribute->isIdentifier() && !$entity->{$method}()) {
continue;
}
$relation = $classMetadata->getRelation(
$attribute->getSerializedKey()
);
$data = $entity->{$method}();
if (
null === $data &&
$relation &&
$relation->isManyToOne() &&
$level > 0
) {
/*
We only serialize the root many-to-one relations to prevent, hopefully,
unlinked and/or duplicated content. For instance, a cart with cartItemList containing
null values for the cart [{ cart => null, ... }] may lead the creation of
CartItem entities explicitly bound to a null Cart instead of the created/updated Cart.
*/
continue;
} elseif ($data instanceof DateTimeInterface) {
$data = $data->format('c');
} elseif (is_object($data) && $data instanceof PhoneNumber) {
$phoneNumberUtil = PhoneNumberUtil::getInstance();
$data = $phoneNumberUtil->format(
$data,
PhoneNumberFormat::INTERNATIONAL
);
} elseif (
is_object($data) &&
$relation &&
$this->mapping->hasClassMetadata(
$relation->getTargetEntity()
)
) {
$relationClassMetadata = $this->mapping->getClassMetadata(
$relation->getTargetEntity()
);
if (!$relationClassMetadata->hasIdentifierAttribute()) {
$data = $this->recursiveSerialize(
$data,
$relation->getTargetEntity(),
$level + 1,
$context
);
} else {
$idAttribute = $relationClassMetadata->getIdentifierAttribute();
$idGetter =
'get' . ucfirst($idAttribute->getAttributeName());
if (
method_exists($data, $idGetter) &&
$data->{$idGetter}()
) {
$data = $data->{$idGetter}();
} elseif ($relation->isManyToOne()) {
if ($level > 0) {
continue;
} else {
throw new SdkException(
'Case not allowed for now'
);
}
}
}
} elseif (is_array($data)) {
$newData = [];
foreach ($data as $key => $item) {
if ($item instanceof DateTimeInterface) {
$newData[$key] = $item->format('c');
} elseif (
is_object($item) &&
$relation &&
$this->mapping->hasClassMetadata(
$relation->getTargetEntity()
)
) {
$serializeRelation =
!empty($context['serializeRelations']) &&
in_array(
$relation->getSerializedKey(),
$context['serializeRelations']
);
$newData[$key] = $this->recursiveSerialize(
$item,
$relation->getTargetEntity(),
$level + 1,
['serializeRelation' => $serializeRelation]
);
} else {
$newData[$key] = $item;
}
}
$data = $newData;
}
$key = $attribute->getSerializedKey();
$out[$key] = $data;
}
}
return $out;
}
private function getClassMetadataFromId(string $id): ?ClassMetadata
{
$key = $this->mapping->getKeyFromId($id);
return $this->mapping->getClassMetadataByKey($key);
}
private function getClassMetadata(object $entity): ClassMetadata
{
return $this->mapping->getClassMetadata(get_class($entity));
}
private function throwIfAttributeIsNotWritable(
object $instance,
string $attribute
): void {
if (!$this->propertyAccessor->isWritable($instance, $attribute)) {
throw new MissingSetterException(
sprintf(
'Property %s is not writable for class %s. Please make it writable. You can check the property-access documentation here : https://symfony.com/doc/current/components/property_access.html#writing-to-objects',
$attribute,
get_class($instance)
)
);
}
}
private function setDateTimeValue(
object $instance,
string $attributeName,
string $value
): void {
try {
$this->propertyAccessor->setValue(
$instance,
$attributeName,
new DateTime($value)
);
} catch (InvalidArgumentException $e) {
if (
false ===
mb_strpos(
$e->getMessage(),
'Expected argument of type "DateTimeImmutable", "DateTime" given' // symfony < 4.4 message
) &&
false ===
mb_strpos(
$e->getMessage(),
'Expected argument of type "DateTimeImmutable", "instance of DateTime" given' // symfony >= 4.4 message
)
) {
// not an issue with DateTimeImmutable, then rethrow exception
throw $e;
}
// The excepted value is a DateTimeImmutable, so let's do that
$this->propertyAccessor->setValue(
$instance,
$attributeName,
new DateTimeImmutable($value)
);
}
}
}