ClassDiscriminatorFromClassMetadata.php 2.7 KB

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