-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathObjectToObjectTransformer.php
559 lines (461 loc) · 18.6 KB
/
ObjectToObjectTransformer.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<?php
declare(strict_types=1);
/*
* This file is part of rekalogika/mapper package.
*
* (c) Priyadi Iman Nurcahyo <https://rekalogika.dev>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
namespace Rekalogika\Mapper\Transformer\Implementation;
use Psr\Container\ContainerInterface;
use Rekalogika\Mapper\Context\Context;
use Rekalogika\Mapper\Context\MapperOptions;
use Rekalogika\Mapper\Exception\InvalidArgumentException;
use Rekalogika\Mapper\ObjectCache\ObjectCache;
use Rekalogika\Mapper\Proxy\ProxyFactoryInterface;
use Rekalogika\Mapper\ServiceMethod\ServiceMethodRunner;
use Rekalogika\Mapper\SubMapper\SubMapperFactoryInterface;
use Rekalogika\Mapper\Transformer\Exception\ClassNotInstantiableException;
use Rekalogika\Mapper\Transformer\Exception\InstantiationFailureException;
use Rekalogika\Mapper\Transformer\Exception\NotAClassException;
use Rekalogika\Mapper\Transformer\Exception\UninitializedSourcePropertyException;
use Rekalogika\Mapper\Transformer\Exception\UnsupportedPropertyMappingException;
use Rekalogika\Mapper\Transformer\MainTransformerAwareInterface;
use Rekalogika\Mapper\Transformer\MainTransformerAwareTrait;
use Rekalogika\Mapper\Transformer\Model\AdderRemoverProxy;
use Rekalogika\Mapper\Transformer\Model\ConstructorArguments;
use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\ObjectToObjectMetadata;
use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\ObjectToObjectMetadataFactoryInterface;
use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\PropertyMapping;
use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\Visibility;
use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\WriteMode;
use Rekalogika\Mapper\Transformer\TransformerInterface;
use Rekalogika\Mapper\Transformer\TypeMapping;
use Rekalogika\Mapper\Transformer\Util\ReaderWriter;
use Rekalogika\Mapper\Util\TypeCheck;
use Rekalogika\Mapper\Util\TypeFactory;
use Rekalogika\Mapper\Util\TypeGuesser;
use Symfony\Component\PropertyInfo\Type;
final class ObjectToObjectTransformer implements TransformerInterface, MainTransformerAwareInterface
{
use MainTransformerAwareTrait;
private ReaderWriter $readerWriter;
public function __construct(
private ObjectToObjectMetadataFactoryInterface $objectToObjectMetadataFactory,
private ContainerInterface $propertyMapperLocator,
private SubMapperFactoryInterface $subMapperFactory,
private ProxyFactoryInterface $proxyFactory,
ReaderWriter $readerWriter = null,
) {
$this->readerWriter = $readerWriter ?? new ReaderWriter();
}
public function transform(
mixed $source,
mixed $target,
?Type $sourceType,
?Type $targetType,
Context $context
): mixed {
if ($targetType === null) {
throw new InvalidArgumentException('Target type must not be null.', context: $context);
}
// verify source
if (!is_object($source)) {
throw new InvalidArgumentException(sprintf('The source must be an object, "%s" given.', get_debug_type($source)), context: $context);
}
$sourceType = TypeGuesser::guessTypeFromVariable($source);
$sourceClass = $sourceType->getClassName();
if (null === $sourceClass || !\class_exists($sourceClass)) {
throw new InvalidArgumentException("Cannot get the class name for the source type.", context: $context);
}
// verify target
$targetClass = $targetType->getClassName();
if (null === $targetClass) {
throw new InvalidArgumentException("Cannot get the class name for the target type.", context: $context);
}
if (!\class_exists($targetClass) && !\interface_exists($targetClass)) {
throw new NotAClassException($targetClass, context: $context);
}
// if sourceType and targetType are the same, just return the source
if (null === $target && TypeCheck::isSomewhatIdentical($sourceType, $targetType)) {
return $source;
}
// get the object to object mapping metadata
$objectToObjectMetadata = $this->objectToObjectMetadataFactory
->createObjectToObjectMetadata($sourceClass, $targetClass);
// disregard target if target is read only or target value reading is
// disabled
if (
$objectToObjectMetadata->isTargetReadOnly()
|| !$context(MapperOptions::class)?->readTargetValue
) {
$target = null;
}
// initialize target if target is null
if (null === $target) {
$canUseTargetProxy = $objectToObjectMetadata->canUseTargetProxy()
&& $context(MapperOptions::class)?->lazyLoading;
if ($canUseTargetProxy) {
$target = $this->instantiateTargetProxy(
source: $source,
objectToObjectMetadata: $objectToObjectMetadata,
context: $context
);
} else {
$target = $this->instantiateRealTarget(
source: $source,
objectToObjectMetadata: $objectToObjectMetadata,
context: $context
);
}
} else {
$canUseTargetProxy = false;
if (!is_object($target)) {
throw new InvalidArgumentException(sprintf('The target must be an object, "%s" given.', get_debug_type($target)), context: $context);
}
}
// save object to cache
$context(ObjectCache::class)?->saveTarget(
source: $source,
targetType: $targetType,
target: $target,
);
// map properties if it is not a proxy
if (!$canUseTargetProxy) {
$this->readSourceAndWriteTarget(
source: $source,
target: $target,
propertyMappings: $objectToObjectMetadata->getPropertyMappings(),
context: $context
);
}
return $target;
}
private function instantiateRealTarget(
object $source,
ObjectToObjectMetadata $objectToObjectMetadata,
Context $context
): object {
$targetClass = $objectToObjectMetadata->getTargetClass();
// check if class is valid & instantiable
if (!$objectToObjectMetadata->isInstantiable()) {
throw new ClassNotInstantiableException($targetClass, context: $context);
}
$constructorArguments = $this->generateConstructorArguments(
source: $source,
objectToObjectMetadata: $objectToObjectMetadata,
context: $context
);
try {
$reflectionClass = new \ReflectionClass($targetClass);
return $reflectionClass
->newInstanceArgs($constructorArguments->getArguments());
} catch (\TypeError | \ReflectionException $e) {
throw new InstantiationFailureException(
source: $source,
targetClass: $targetClass,
constructorArguments: $constructorArguments->getArguments(),
unsetSourceProperties: $constructorArguments->getUnsetSourceProperties(),
previous: $e,
context: $context
);
}
}
private function instantiateTargetProxy(
object $source,
ObjectToObjectMetadata $objectToObjectMetadata,
Context $context
): object {
$targetClass = $objectToObjectMetadata->getTargetClass();
// check if class is valid & instantiable
if (!$objectToObjectMetadata->isInstantiable()) {
throw new ClassNotInstantiableException($targetClass, context: $context);
}
// create proxy initializer. this initializer will be executed when the
// proxy is first accessed
$initializer = function (object $target) use (
$source,
$objectToObjectMetadata,
$context,
): void {
// if the constructor is lazy, run it here
if (!$objectToObjectMetadata->constructorIsEager()) {
$target = $this->runConstructorManually(
source: $source,
target: $target,
objectToObjectMetadata: $objectToObjectMetadata,
context: $context
);
}
// map lazy properties
$this->readSourceAndWriteTarget(
source: $source,
target: $target,
propertyMappings: $objectToObjectMetadata->getLazyPropertyMappings(),
context: $context
);
};
// instantiate the proxy
$target = $this->proxyFactory->createProxy(
$targetClass,
$initializer,
$objectToObjectMetadata->getTargetProxySkippedProperties()
);
// if the constructor is eager, run it here
if ($objectToObjectMetadata->constructorIsEager()) {
$target = $this->runConstructorManually(
source: $source,
target: $target,
objectToObjectMetadata: $objectToObjectMetadata,
context: $context
);
}
// map eager properties
$this->readSourceAndWriteTarget(
source: $source,
target: $target,
propertyMappings: $objectToObjectMetadata->getEagerPropertyMappings(),
context: $context
);
return $target;
}
private function runConstructorManually(
object $source,
object $target,
ObjectToObjectMetadata $objectToObjectMetadata,
Context $context
): object {
if (!\method_exists($target, '__construct')) {
return $target;
}
$constructorArguments = $this->generateConstructorArguments(
source: $source,
objectToObjectMetadata: $objectToObjectMetadata,
context: $context
);
$arguments = $constructorArguments->getArguments();
try {
/**
* @psalm-suppress DirectConstructorCall
* @psalm-suppress MixedMethodCall
*/
$target->__construct(...$arguments);
} catch (\TypeError | \ReflectionException $e) {
throw new InstantiationFailureException(
source: $source,
targetClass: $target::class,
constructorArguments: $constructorArguments->getArguments(),
unsetSourceProperties: $constructorArguments->getUnsetSourceProperties(),
previous: $e,
context: $context
);
}
return $target;
}
private function generateConstructorArguments(
object $source,
ObjectToObjectMetadata $objectToObjectMetadata,
Context $context
): ConstructorArguments {
$propertyMappings = $objectToObjectMetadata->getConstructorPropertyMappings();
$constructorArguments = new ConstructorArguments();
foreach ($propertyMappings as $propertyMapping) {
try {
/** @var mixed */
$targetPropertyValue = $this->transformValue(
propertyMapping: $propertyMapping,
source: $source,
target: null,
context: $context
);
$constructorArguments->addArgument(
$propertyMapping->getTargetProperty(),
$targetPropertyValue
);
} catch (UninitializedSourcePropertyException $e) {
$sourceProperty = $e->getPropertyName();
$constructorArguments->addUnsetSourceProperty($sourceProperty);
continue;
} catch (UnsupportedPropertyMappingException $e) {
continue;
}
}
return $constructorArguments;
}
/**
* @param array<int,PropertyMapping> $propertyMappings
*/
private function readSourceAndWriteTarget(
object $source,
object $target,
array $propertyMappings,
Context $context
): void {
foreach ($propertyMappings as $propertyMapping) {
$this->readSourcePropertyAndWriteTargetProperty(
source: $source,
target: $target,
propertyMapping: $propertyMapping,
context: $context
);
}
}
private function readSourcePropertyAndWriteTargetProperty(
object $source,
object $target,
PropertyMapping $propertyMapping,
Context $context
): void {
$targetWriteMode = $propertyMapping->getTargetWriteMode();
$targetWriteVisibility = $propertyMapping->getTargetWriteVisibility();
if (
in_array($targetWriteMode, [
WriteMode::None,
WriteMode::Constructor,
], true)
) {
return;
}
if ($targetWriteVisibility !== Visibility::Public) {
return;
}
try {
/** @var mixed */
$targetPropertyValue = $this->transformValue(
propertyMapping: $propertyMapping,
source: $source,
target: $target,
context: $context
);
} catch (UninitializedSourcePropertyException $e) {
return;
} catch (UnsupportedPropertyMappingException $e) {
return;
}
// write
$this->readerWriter->writeTargetProperty(
target: $target,
propertyMapping: $propertyMapping,
value: $targetPropertyValue,
context: $context
);
}
/**
* @param object|null $target Target is null if the transformation is for a
* constructor argument
*/
private function transformValue(
PropertyMapping $propertyMapping,
object $source,
?object $target,
Context $context
): mixed {
// if a custom property mapper is set, then use it
if ($serviceMethodSpecification = $propertyMapping->getPropertyMapper()) {
$serviceMethodRunner = ServiceMethodRunner::create(
serviceLocator: $this->propertyMapperLocator,
mainTransformer: $this->getMainTransformer(),
subMapperFactory: $this->subMapperFactory
);
return $serviceMethodRunner->run(
serviceMethodSpecification: $serviceMethodSpecification,
source: $source,
targetType: null,
context: $context
);
}
// if source property name is null, continue. there is nothing to
// transform
$sourceProperty = $propertyMapping->getSourceProperty();
if ($sourceProperty === null) {
throw new UnsupportedPropertyMappingException();
}
// get the value of the source property
/** @var mixed */
$sourcePropertyValue = $this->readerWriter
->readSourceProperty($source, $propertyMapping, $context);
// short circuit. optimization for transformation between scalar and
// null, so that we don't have to go through the main transformer for
// this common task.
if ($context(MapperOptions::class)?->objectToObjectScalarShortCircuit) {
// if source is null & target accepts null, we set the
// target to null
if ($propertyMapping->targetCanAcceptNull() && $sourcePropertyValue === null) {
return null;
}
// if the the source is null or scalar, and the target is a scalar
$targetScalarType = $propertyMapping->getTargetScalarType();
if ($targetScalarType !== null) {
if ($sourcePropertyValue === null) {
return match ($targetScalarType) {
'int' => 0,
'float' => 0.0,
'string' => '',
'bool' => false,
'null' => null,
};
} elseif (is_scalar($sourcePropertyValue)) {
return match ($targetScalarType) {
'int' => (int) $sourcePropertyValue,
'float' => (float) $sourcePropertyValue,
'string' => (string) $sourcePropertyValue,
'bool' => (bool) $sourcePropertyValue,
'null' => null,
};
}
}
}
// get the value of the target property if the target is an object and
// target value reading is enabled
if (
is_object($target)
&& $context(MapperOptions::class)?->readTargetValue
) {
// if this is for a property mapping, not a constructor argument
/** @var mixed */
$targetPropertyValue = $this->readerWriter->readTargetProperty(
$target,
$propertyMapping,
$context
);
} else {
// if this is for a constructor argument, we don't have an existing
// value
$targetPropertyValue = null;
}
// if we get an AdderRemoverProxy, change the target type
$targetTypes = $propertyMapping->getTargetTypes();
if ($targetPropertyValue instanceof AdderRemoverProxy) {
$key = $targetTypes[0]->getCollectionKeyTypes();
$value = $targetTypes[0]->getCollectionValueTypes();
$targetTypes = [
TypeFactory::objectWithKeyValue(
\ArrayAccess::class,
$key[0],
$value[0]
)
];
}
// guess source type, and get the compatible type from metadata, so
// we can preserve generics information
$guessedSourceType = TypeGuesser::guessTypeFromVariable($sourcePropertyValue);
$sourceType = $propertyMapping->getCompatibleSourceType($guessedSourceType);
// transform the value
/** @var mixed */
$targetPropertyValue = $this->getMainTransformer()->transform(
source: $sourcePropertyValue,
target: $targetPropertyValue,
sourceType: $sourceType,
targetTypes: $targetTypes,
context: $context,
path: $propertyMapping->getTargetProperty(),
);
return $targetPropertyValue;
}
public function getSupportedTransformation(): iterable
{
yield new TypeMapping(TypeFactory::object(), TypeFactory::object(), true);
}
}