Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Mapping/ClassDiscriminatorFromClassMetadata.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Serializer\Mapping;
13
14 use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
15
16 /**
17 * @author Samuel Roze <[email protected]>
18 */
19 class ClassDiscriminatorFromClassMetadata implements ClassDiscriminatorResolverInterface
20 {
21 private array $mappingForMappedObjectCache = [];
22
23 public function __construct(
24 private readonly ClassMetadataFactoryInterface $classMetadataFactory,
25 ) {
26 }
27
28 public function getMappingForClass(string $class): ?ClassDiscriminatorMapping
29 {
30 if ($this->classMetadataFactory->hasMetadataFor($class)) {
31 return $this->classMetadataFactory->getMetadataFor($class)->getClassDiscriminatorMapping();
32 }
33
34 return null;
35 }
36
37 public function getMappingForMappedObject(object|string $object): ?ClassDiscriminatorMapping
38 {
39 if ($this->classMetadataFactory->hasMetadataFor($object)) {
40 $metadata = $this->classMetadataFactory->getMetadataFor($object);
41
42 if (null !== $metadata->getClassDiscriminatorMapping()) {
43 return $metadata->getClassDiscriminatorMapping();
44 }
45 }
46
47 $cacheKey = \is_object($object) ? $object::class : $object;
48 if (!\array_key_exists($cacheKey, $this->mappingForMappedObjectCache)) {
49 $this->mappingForMappedObjectCache[$cacheKey] = $this->resolveMappingForMappedObject($object);
50 }
51
52 return $this->mappingForMappedObjectCache[$cacheKey];
53 }
54
55 public function getTypeForMappedObject(object|string $object): ?string
56 {
57 if (null === $mapping = $this->getMappingForMappedObject($object)) {
58 return null;
59 }
60
61 return $mapping->getMappedObjectType($object);
62 }
63
64 private function resolveMappingForMappedObject(object|string $object): ?ClassDiscriminatorMapping
65 {
66 $reflectionClass = new \ReflectionClass($object);
67 if ($parentClass = $reflectionClass->getParentClass()) {
68 if (null !== ($parentMapping = $this->getMappingForMappedObject($parentClass->getName()))) {
69 return $parentMapping;
70 }
71 }
72
73 foreach ($reflectionClass->getInterfaceNames() as $interfaceName) {
74 if (null !== ($interfaceMapping = $this->getMappingForMappedObject($interfaceName))) {
75 return $interfaceMapping;
76 }
77 }
78
79 return null;
80 }
81 }