ClassMetadataFactory.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\Factory;
  11. use Symfony\Component\Serializer\Mapping\ClassMetadata;
  12. use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
  13. /**
  14. * Returns a {@link ClassMetadata}.
  15. *
  16. * @author Kévin Dunglas <dunglas@gmail.com>
  17. */
  18. class ClassMetadataFactory implements ClassMetadataFactoryInterface
  19. {
  20. use ClassResolverTrait;
  21. private $loader;
  22. /**
  23. * @var array
  24. */
  25. private $loadedClasses;
  26. public function __construct(LoaderInterface $loader)
  27. {
  28. $this->loader = $loader;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getMetadataFor($value)
  34. {
  35. $class = $this->getClass($value);
  36. if (isset($this->loadedClasses[$class])) {
  37. return $this->loadedClasses[$class];
  38. }
  39. $classMetadata = new ClassMetadata($class);
  40. $this->loader->loadClassMetadata($classMetadata);
  41. $reflectionClass = $classMetadata->getReflectionClass();
  42. // Include metadata from the parent class
  43. if ($parent = $reflectionClass->getParentClass()) {
  44. $classMetadata->merge($this->getMetadataFor($parent->name));
  45. }
  46. // Include metadata from all implemented interfaces
  47. foreach ($reflectionClass->getInterfaces() as $interface) {
  48. $classMetadata->merge($this->getMetadataFor($interface->name));
  49. }
  50. return $this->loadedClasses[$class] = $classMetadata;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function hasMetadataFor($value)
  56. {
  57. return \is_object($value) || (\is_string($value) && (class_exists($value) || interface_exists($value, false)));
  58. }
  59. }