Skip to content

Commit 3576a57

Browse files
soyukafabpot
authored andcommitted
[ObjectMapper] cache attributes in memory
1 parent c228caa commit 3576a57

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/Symfony/Component/ObjectMapper/Metadata/ReflectionObjectMapperMetadataFactory.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,27 @@
2121
*/
2222
final class ReflectionObjectMapperMetadataFactory implements ObjectMapperMetadataFactoryInterface
2323
{
24+
private array $reflectionClassCache = [];
25+
private array $attributesCache = [];
26+
2427
public function create(object $object, ?string $property = null, array $context = []): array
2528
{
2629
try {
27-
$refl = new \ReflectionClass($object);
28-
$mapTo = [];
29-
foreach (($property ? $refl->getProperty($property) : $refl)->getAttributes(Map::class, \ReflectionAttribute::IS_INSTANCEOF) as $mapAttribute) {
30-
$map = $mapAttribute->newInstance();
31-
$mapTo[] = new Mapping($map->target, $map->source, $map->if, $map->transform);
30+
$key = $object::class.($property ?? '');
31+
32+
if (isset($this->attributesCache[$key])) {
33+
return $this->attributesCache[$key];
34+
}
35+
36+
$refl = $this->reflectionClassCache[$object::class] ??= new \ReflectionClass($object);
37+
$attributes = ($property ? $refl->getProperty($property) : $refl)->getAttributes(Map::class, \ReflectionAttribute::IS_INSTANCEOF);
38+
$mappings = [];
39+
foreach ($attributes as $attribute) {
40+
$map = $attribute->newInstance();
41+
$mappings[] = new Mapping($map->target, $map->source, $map->if, $map->transform);
3242
}
3343

34-
return $mapTo;
44+
return $this->attributesCache[$key] = $mappings;
3545
} catch (\ReflectionException $e) {
3646
throw new MappingException($e->getMessage(), $e->getCode(), $e);
3747
}

0 commit comments

Comments
 (0)