Repository navigation
Expand file tree
/
Copy pathObjectMapper.php
More file actions
605 lines (514 loc) · 27.7 KB
/
Copy pathObjectMapper.php
File metadata and controls
605 lines (514 loc) · 27.7 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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\ObjectMapper;
use Psr\Container\ContainerInterface;
use Symfony\Component\ObjectMapper\Condition\ClassRuleConditionCallableInterface;
use Symfony\Component\ObjectMapper\Exception\MappingException;
use Symfony\Component\ObjectMapper\Exception\MappingTransformException;
use Symfony\Component\ObjectMapper\Exception\NoSuchCallableException;
use Symfony\Component\ObjectMapper\Exception\NoSuchPropertyException;
use Symfony\Component\ObjectMapper\Metadata\ClassMetadataFactoryInterface;
use Symfony\Component\ObjectMapper\Metadata\EnumMappingMetadataFactory;
use Symfony\Component\ObjectMapper\Metadata\Mapping;
use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface;
use Symfony\Component\ObjectMapper\Metadata\PropertyMetadataFactoryInterface;
use Symfony\Component\ObjectMapper\Metadata\PropertyNameCollectionFactoryInterface;
use Symfony\Component\ObjectMapper\Metadata\PropertyReadability;
use Symfony\Component\ObjectMapper\Metadata\PropertyTypeMappingMetadataFactory;
use Symfony\Component\ObjectMapper\Metadata\ReflectionClassMetadataFactory;
use Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory;
use Symfony\Component\ObjectMapper\Metadata\ReflectionPropertyMetadataFactory;
use Symfony\Component\ObjectMapper\Metadata\ReflectionPropertyNameCollectionFactory;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException as PropertyAccessorNoSuchPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\VarExporter\LazyObjectInterface;
/**
* Object to object mapper.
*
* @phpstan-import-type PropertyMetadata from PropertyMetadataFactoryInterface
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
final class ObjectMapper implements ObjectMapperInterface, ObjectMapperAwareInterface
{
/**
* Tracks recursive references.
*/
private ?\WeakMap $objectMap = null;
private readonly ClassMetadataFactoryInterface $classMetadataFactory;
private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory;
private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory;
/**
* @var array<class-string, \ReflectionClass>
*/
private array $reflectionClasses = [];
/**
* Lazy ghosts created by this mapper whose constructor has not run yet.
*/
private ?\WeakMap $pendingConstruction = null;
/**
* @var array<class-string, array<class-string, Mapping[]>>
*/
private array $classMappingsByTarget = [];
/**
* Saves a call to the property metadata factory for each property of each mapped object.
*
* @var array<class-string, array<class-string, array<string, PropertyMetadata>>>
*/
private array $propertyMetadata = [];
public function __construct(
private readonly ObjectMapperMetadataFactoryInterface $metadataFactory = new PropertyTypeMappingMetadataFactory(new EnumMappingMetadataFactory(new ReflectionObjectMapperMetadataFactory())),
private readonly ?PropertyAccessorInterface $propertyAccessor = null,
private readonly ?ContainerInterface $transformCallableLocator = null,
private readonly ?ContainerInterface $conditionCallableLocator = null,
private ?ObjectMapperInterface $objectMapper = null,
?ClassMetadataFactoryInterface $classMetadataFactory = null,
?PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory = null,
?PropertyMetadataFactoryInterface $propertyMetadataFactory = null,
) {
$this->classMetadataFactory = $classMetadataFactory ?? new ReflectionClassMetadataFactory($metadataFactory);
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory ?? new ReflectionPropertyNameCollectionFactory();
$this->propertyMetadataFactory = $propertyMetadataFactory ?? new ReflectionPropertyMetadataFactory($metadataFactory, $this->classMetadataFactory, $propertyAccessor);
}
public function map(object $source, object|string|null $target = null): object
{
$constructTarget = false;
if (\is_object($target) && isset($this->pendingConstruction[$target])) {
unset($this->pendingConstruction[$target]);
$constructTarget = true;
}
if ($this->objectMap) {
return $this->doMap($source, $target, $this->objectMap, $constructTarget);
}
$this->objectMap = new \WeakMap();
try {
return $this->doMap($source, $target, $this->objectMap, $constructTarget);
} finally {
$this->objectMap = null;
}
}
private function doMap(object $source, object|string|null $target, \WeakMap $objectMap, bool $constructTarget = false): object
{
// the class metadata is keyed by the target too: resolving it from the source alone still needs the metadata factory
$metadata = null === $target ? $this->metadataFactory->create($source) : null;
$map = null === $target ? $this->getMapTarget($metadata, null, $source, null, true) : null;
$target ??= $map?->target;
$mappingToObject = \is_object($target);
if (!$target) {
throw new MappingException(\sprintf('Mapping target not found for source "%s".', get_debug_type($source)));
}
if (\is_string($target) && !class_exists($target)) {
throw new MappingException(\sprintf('Mapping target class "%s" does not exist for source "%s".', $target, get_debug_type($source)));
}
$targetRefl = $this->getReflectionClass($target);
$declaredTarget = $mappedTarget = $mappingToObject ? $target : $targetRefl->newInstanceWithoutConstructor();
$classMetadata = $this->classMetadataFactory->create($source, $declaredTarget);
$pairMetadata = &$this->propertyMetadata[$source::class][$declaredTarget::class];
if (null === $metadata) {
$metadata = $classMetadata['classMappings'];
$map = $this->getMapTarget($this->classMappingsByTarget[$source::class][$targetRefl->name] ??= $this->filterMetadataByTarget($metadata, $target), null, $source, null, false);
}
if (!$metadata && $classMetadata['classMappingsFromTarget']) {
$map = $this->getMapTarget($classMetadata['classMappingsFromTarget'], null, $source, null, false);
}
if ($map && $map->transform) {
$mappedTarget = $this->applyTransforms($map, $mappedTarget, $source, null);
if (!\is_object($mappedTarget)) {
throw new MappingTransformException(\sprintf('Cannot map "%s" to a non-object target of type "%s".', get_debug_type($source), get_debug_type($mappedTarget)));
}
}
if (!is_a($mappedTarget, $targetRefl->getName(), false)) {
throw new MappingException(\sprintf('Expected the mapped object to be an instance of "%s" but got "%s".', $targetRefl->getName(), get_debug_type($mappedTarget)));
}
// a child class returned by a transform can have setters that the metadata of the declared target does not know about
$writeDirectly = !$this->propertyAccessor || $mappedTarget::class === $declaredTarget::class;
$objectMap[$source] = $mappedTarget;
$this->initializeLazyObject($source);
$sourceVars = null;
$ctorArguments = [];
if (!$mappingToObject || $constructTarget) {
foreach ($classMetadata['constructorParameters'] as $parameterName => $parameter) {
if ($parameter['readOnly'] && $targetRefl->getProperty($parameterName)->isInitialized($mappedTarget)) {
continue;
}
$propertyMetadata = $pairMetadata[$parameterName] ??= $this->propertyMetadataFactory->create($source, $declaredTarget, $parameterName);
if ($this->isReadable($source, $parameterName, $propertyMetadata['readability'], $sourceVars)) {
$ctorArguments[$parameterName] = $this->getRawValue($source, $parameterName, $propertyMetadata['sourceDeclared'], $propertyMetadata['readability']);
} else {
$ctorArguments[$parameterName] = $parameter['hasDefault'] ? $parameter['default'] : null;
}
}
}
$mapToProperties = [];
$targetName = $targetRefl->getName();
$explicitTargets = [];
$mergeTargets = [];
$implicitValues = [];
foreach ($this->propertyNameCollectionFactory->create($classMetadata['readMetadataFromTarget'] ? $declaredTarget : $source) as $propertyName) {
$propertyMetadata = $pairMetadata[$propertyName] ??= $this->propertyMetadataFactory->create($source, $declaredTarget, $propertyName);
foreach ($propertyMetadata['mappings'] as $propertyMapping) {
$mapping = $propertyMapping['mapping'];
$sourcePropertyName = $propertyMapping['sourceProperty'];
$targetPropertyName = $propertyMapping['targetProperty'];
if (false === $if = $mapping->if) {
if (!isset($explicitTargets[$targetPropertyName])) {
unset($ctorArguments[$targetPropertyName]);
}
continue;
}
$fn = null;
$isClassRule = false;
if ($if) {
$fn = $this->getCallable($if, $this->conditionCallableLocator, ConditionCallableInterface::class);
$isClassRule = $fn instanceof ClassRuleConditionCallableInterface;
if ($isClassRule && !$this->call($fn, null, $source, $mappedTarget)) {
continue;
}
}
if ($propertyMapping['sourceDeclared'] && !$this->isReadable($source, $sourcePropertyName, $propertyMapping['sourceReadability'], $sourceVars)) {
continue;
}
$value = $this->getRawValue($source, $sourcePropertyName, $propertyMapping['sourceDeclared'], $propertyMapping['sourceReadability']);
if ($fn && !$isClassRule && !$this->call($fn, $value, $source, $mappedTarget)) {
if (!isset($explicitTargets[$targetPropertyName])) {
unset($ctorArguments[$targetPropertyName]);
}
continue;
}
$writable = $writeDirectly && $propertyMapping['targetWritable'];
$sourceValue = $value;
$value = $this->getSourceValue($source, $mappedTarget, $value, $objectMap, $mapping, $propertyMapping['targetPropertyClass'], $declaredTarget, $targetPropertyName, $ctorArguments, $writable, $mergeTargets[$targetPropertyName] ?? null);
// a later mapping of the same property must not write into an object copied as is from the source
$mergeTargets[$targetPropertyName] = \is_object($value) && $value !== $sourceValue ? $value : null;
$explicitTargets[$targetPropertyName] = true;
$this->storeValue($targetPropertyName, $mapToProperties, $ctorArguments, $value, $writable);
}
if ($propertyMetadata['mappings']) {
continue;
}
if ($propertyMetadata['targetHasProperty']) {
if (!$this->isReadable($source, $propertyName, $propertyMetadata['readability'], $sourceVars)) {
continue;
}
if (null !== $propertyMetadata['initializedKey'] && !\array_key_exists($propertyMetadata['initializedKey'], $sourceVars ??= (array) $source)) {
continue;
}
$writable = $writeDirectly && $propertyMetadata['targetWritable'];
$implicitValues[$propertyName] = [$this->getSourceValue($source, $mappedTarget, $this->getRawValue($source, $propertyName, $propertyMetadata['sourceDeclared'], $propertyMetadata['readability']), $objectMap, $propertyMetadata['sameNameMapping'], $propertyMetadata['targetPropertyClass'], $declaredTarget, $propertyName, $ctorArguments, $writable), $writable];
continue;
}
if (!$this->isReadable($source, $propertyName, $propertyMetadata['mergeReadability'], $sourceVars)) {
continue;
}
$rawValue = $this->getRawValue($source, $propertyName, $propertyMetadata['sourceDeclared'], $propertyMetadata['mergeReadability']);
if (
\is_object($rawValue)
// a self-referencing relation maps to the same target by definition, merging it would overwrite the target with the related object's values
&& !$rawValue instanceof $source
&& !$objectMap->offsetExists($rawValue)
&& ($innerMetadata = $this->metadataFactory->create($rawValue))
&& array_any($innerMetadata, static fn (Mapping $m): bool => \is_string($m->target) && is_a($targetName, $m->target, true))
) {
($this->objectMapper ?? $this)->map($rawValue, $mappedTarget);
}
}
foreach ($implicitValues as $propertyName => [$value, $writable]) {
if (!isset($explicitTargets[$propertyName])) {
$this->storeValue($propertyName, $mapToProperties, $ctorArguments, $value, $writable);
}
}
if ((!$mappingToObject || $constructTarget) && !$map?->transform && $classMetadata['hasConstructor']
&& ($ctorArguments || !$classMetadata['requiredConstructorParameters'])
) {
try {
$mappedTarget->__construct(...$ctorArguments);
} catch (\ReflectionException $e) {
throw new MappingException($e->getMessage(), $e->getCode(), $e);
}
}
foreach ($mapToProperties as $property => [$value, $writable]) {
if (!$writable) {
// the metadata of the declared target cannot tell for the child class a transform returned
$accessorWritable = $mappedTarget::class === $declaredTarget::class ? ($pairMetadata[$property] ??= $this->propertyMetadataFactory->create($source, $declaredTarget, $property))['targetAccessorWritable'] : null;
if ($accessorWritable ?? $this->propertyAccessor->isWritable($mappedTarget, $property)) {
$this->propertyAccessor->setValue($mappedTarget, $property, $value);
}
continue;
}
try {
$mappedTarget->{$property} = $value;
} catch (\TypeError $e) {
if (!$this->propertyAccessor) {
throw $e;
}
// the accessor converts a DateTime to a DateTimeImmutable and back, or throws its own exception
$this->propertyAccessor->setValue($mappedTarget, $property, $value);
}
}
return $mappedTarget;
}
/**
* @param PropertyReadability::* $readability
* @param ?array $sourceVars the array cast of the source, computed on first use and shared by the whole map() call
*/
private function isReadable(object $source, string $propertyName, int $readability, ?array &$sourceVars): bool
{
return match ($readability) {
PropertyReadability::ACCESSOR => $this->propertyAccessor->isReadable($source, $propertyName),
PropertyReadability::ALWAYS => true,
PropertyReadability::NEVER => false,
PropertyReadability::INITIALIZED => \array_key_exists($propertyName, $sourceVars ??= (array) $source) || isset($source->{$propertyName}),
PropertyReadability::DYNAMIC => property_exists($source, $propertyName) || isset($source->{$propertyName}),
};
}
/**
* @param PropertyReadability::* $readability
*/
private function getRawValue(object $source, string $propertyName, bool $declared, int $readability): mixed
{
if (PropertyReadability::ACCESSOR === $readability) {
try {
return $this->propertyAccessor->getValue($source, $propertyName);
} catch (PropertyAccessorNoSuchPropertyException $e) {
throw new NoSuchPropertyException($e->getMessage(), $e->getCode(), $e);
}
}
if (!$declared && !property_exists($source, $propertyName) && !isset($source->{$propertyName})) {
throw new NoSuchPropertyException(\sprintf('The property "%s" does not exist on "%s".', $propertyName, get_debug_type($source)));
}
return $source->{$propertyName};
}
/**
* @param array<string, mixed> $ctorArguments
*/
private function getSourceValue(object $source, object $target, mixed $value, \WeakMap $objectMap, ?Mapping $mapping, ?string $targetPropertyClass, object $declaredTarget, string $targetPropertyName, array $ctorArguments, bool $targetWritable, ?object $mergeInto = null): mixed
{
if ($mapping?->transform) {
$value = $this->applyTransforms($mapping, $value, $source, $target);
}
if (
\is_object($value)
&& ($innerMetadata = $this->metadataFactory->create($value, null, $this->getDestinationContext($declaredTarget, $target, $targetPropertyName, $ctorArguments, $targetWritable)))
&& ($innerMetadata = $this->filterMetadataByPropertyType($innerMetadata, $targetPropertyClass))
&& ($mapTo = $this->getMapTarget($innerMetadata, $value, $source, $target, true))
&& (\is_string($mapTo->target) && class_exists($mapTo->target))
) {
$value = $this->applyTransforms($mapTo, $value, $source, $target);
// an already mapped source is reusable only when it matches the target resolved for this property
if ($value === $source && $target instanceof $mapTo->target) {
$value = $target;
} elseif ($objectMap->offsetExists($value) && $objectMap[$value] instanceof $mapTo->target) {
$value = $objectMap[$value];
} else {
if ($mapTo->transform) {
return $value;
}
$refl = $this->getReflectionClass($mapTo->target);
$mapper = $this->objectMapper ?? $this;
// readonly properties cannot be written after the constructor ran, so an object with readonly properties is replaced instead
if ($mergeInto instanceof $mapTo->target && !array_any($this->getReflectionClass($mergeInto)->getProperties(), static fn (\ReflectionProperty $p): bool => $p->isReadOnly())) {
// mapping the previous source first lets a reference to the previous source resolve to the merged object
$this->initializeLazyObject($mergeInto);
return $mapper->map($value, $mergeInto);
}
return $refl->newLazyGhost(function ($target) use ($mapper, $value, $objectMap) {
$previousMap = $this->objectMap;
$this->objectMap = $objectMap;
try {
// the ghost has not run a constructor yet, unlike a caller-supplied target
if ($mapper === $this) {
$objectMap[$value] = $this->doMap($value, $target, $objectMap, true);
} else {
// the decorator calls back into map(), which must still construct the ghost
$this->pendingConstruction ??= new \WeakMap();
$this->pendingConstruction[$target] = true;
$objectMap[$value] = $mapper->map($value, $target);
}
} finally {
unset($this->pendingConstruction[$target]);
$this->objectMap = $previousMap;
}
});
}
}
return $value;
}
/**
* Tells the metadata factory which property the nested value is written into, so that a factory
* can resolve a mapping from the type of that property.
*
* The context is left empty when the mapper cannot write the property: a value that is thrown
* away must not report a mapping error.
*
* @param array<string, mixed> $ctorArguments
*
* @return array<string, mixed>
*/
private function getDestinationContext(object $declaredTarget, object $mappedTarget, string $propertyName, array $ctorArguments, bool $writable): array
{
$writable = $writable || \array_key_exists($propertyName, $ctorArguments) || $this->propertyAccessor?->isWritable($mappedTarget, $propertyName);
return $writable ? ['target' => $declaredTarget::class, 'target_property' => $propertyName] : [];
}
/**
* Store the value either the constructor arguments or as a property to be mapped.
*
* A property that cannot be written with an assignment is written by the PropertyAccessor, or dropped right away when there is none.
*
* @param array<string, array{mixed, bool}> $mapToProperties
* @param array<string, mixed> $ctorArguments
*/
private function storeValue(string $propertyName, array &$mapToProperties, array &$ctorArguments, mixed $value, bool $writable): void
{
if (\array_key_exists($propertyName, $ctorArguments)) {
$ctorArguments[$propertyName] = $value;
return;
}
if ($writable || $this->propertyAccessor) {
$mapToProperties[$propertyName] = [$value, $writable];
}
}
/**
* @param-immediately-invoked-callable $fn
*
* @param callable(): mixed $fn
*/
private function call(callable $fn, mixed $value, object $source, ?object $target = null): mixed
{
if (\is_string($fn)) {
return \call_user_func($fn, $value);
}
return $fn($value, $source, $target);
}
/**
* @param Mapping[] $metadata
*/
private function getMapTarget(array $metadata, mixed $value, object $source, ?object $target, bool $enforceUnique = false): ?Mapping
{
$mapTo = null;
foreach ($metadata as $mapAttribute) {
if (($if = $mapAttribute->if) && ($fn = $this->getCallable($if, $this->conditionCallableLocator, ConditionCallableInterface::class)) && !$this->call($fn, $value, $source, $target)) {
continue;
}
if ($enforceUnique && null !== $mapTo) {
throw new MappingException(\sprintf('Ambiguous mapping for "%s". Multiple #[Map] attributes match. Use the "if" parameter to specify conditions.', get_debug_type($value ?? $source)));
}
$mapTo = $mapAttribute;
}
return $mapTo;
}
/**
* Narrows the class-level mappings of a source to the ones related to the target the caller asked for.
*
* A mapping declaring a subclass of that target is kept: its transform can still produce an
* instance the caller accepts.
*
* @param Mapping[] $metadata
*
* @return Mapping[]
*/
private function filterMetadataByTarget(array $metadata, object|string|null $target): array
{
if (null === $target) {
return $metadata;
}
$targetClass = \is_object($target) ? $target::class : $target;
return array_filter($metadata, static fn (Mapping $m): bool => null === $m->target || is_a($targetClass, $m->target, true) || is_a($m->target, $targetClass, true));
}
/**
* Narrows the mappings of a nested object to the one matching the declared type of the property it is mapped into.
*
* A nested class declaring several #[Map] targets yields one Mapping per target. When the
* destination property is typed, only one of them can be assigned to it, so the mapping is not ambiguous.
* When none of them can be assigned to it, no mapping applies and the value is written as it is.
* Mappings carrying a transform are kept: what lands in the property is the transform's return value,
* not the declared target.
*
* @param Mapping[] $metadata
*
* @return Mapping[]
*/
private function filterMetadataByPropertyType(array $metadata, ?string $propertyClass): array
{
if (null === $propertyClass || !$metadata) {
return $metadata;
}
$filtered = array_values(array_filter($metadata, static fn (Mapping $m): bool => $m->transform || (\is_string($m->target)
&& class_exists($m->target)
&& is_a($m->target, $propertyClass, true))
));
return 1 < \count($filtered) ? $metadata : $filtered;
}
private function applyTransforms(Mapping $map, mixed $value, object $source, ?object $target): mixed
{
if (!$transforms = $map->transform) {
return $value;
}
if (\is_callable($transforms)) {
$transforms = [$transforms];
} elseif (!\is_array($transforms)) {
$transforms = [$transforms];
}
foreach ($transforms as $transform) {
$fn = $this->getCallable($transform, $this->transformCallableLocator, TransformCallableInterface::class);
if ($fn instanceof ObjectMapperAwareInterface) {
$fn = $fn->withObjectMapper($this->objectMapper ?? $this);
}
$value = $fn instanceof MappingAwareTransformCallableInterface
? $fn($value, $source, $target, $map)
: $this->call($fn, $value, $source, $target);
}
return $value;
}
/**
* @param (string|callable(mixed $value, object $object): mixed) $fn
* @param class-string|null $expectedInterface
*/
private function getCallable(string|callable $fn, ?ContainerInterface $locator = null, ?string $expectedInterface = null): callable
{
if (\is_callable($fn)) {
if ($expectedInterface && \is_object($fn) && !$fn instanceof $expectedInterface) {
throw new NoSuchCallableException(\sprintf('"%s" is not a valid callable. Make sure it implements "%s".', get_debug_type($fn), $expectedInterface));
}
return $fn;
}
if ($locator?->has($fn)) {
$callable = $locator->get($fn);
if ($expectedInterface && !$callable instanceof $expectedInterface) {
throw new NoSuchCallableException(\sprintf('"%s" is not a valid callable. Make sure it implements "%s".', $fn, $expectedInterface));
}
return $callable;
}
throw new NoSuchCallableException(\sprintf('"%s" is not a valid callable.', $fn).($expectedInterface ? \sprintf(' If you use a class, make sure it implements "%s".', $expectedInterface) : ''));
}
private function getReflectionClass(object|string $objectOrClass): \ReflectionClass
{
$class = \is_object($objectOrClass) ? $objectOrClass::class : $objectOrClass;
try {
return $this->reflectionClasses[$class] ??= new \ReflectionClass($class);
} catch (\ReflectionException $e) {
throw new MappingException($e->getMessage(), $e->getCode(), $e);
}
}
private function initializeLazyObject(object $source): void
{
if ($source instanceof LazyObjectInterface) {
$source->initializeLazyObject();
} elseif (($refl = $this->getReflectionClass($source))->isUninitializedLazyObject($source)) {
$refl->initializeLazyObject($source);
}
}
public function withObjectMapper(ObjectMapperInterface $objectMapper): static
{
$clone = clone $this;
$clone->objectMapper = $objectMapper;
$clone->pendingConstruction = null;
return $clone;
}
}