LazyLoadingMetadataFactory.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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\Validator\Mapping\Factory;
  11. use Psr\Cache\CacheItemPoolInterface;
  12. use Symfony\Component\Validator\Exception\NoSuchMetadataException;
  13. use Symfony\Component\Validator\Mapping\ClassMetadata;
  14. use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
  15. /**
  16. * Creates new {@link ClassMetadataInterface} instances.
  17. *
  18. * Whenever {@link getMetadataFor()} is called for the first time with a given
  19. * class name or object of that class, a new metadata instance is created and
  20. * returned. On subsequent requests for the same class, the same metadata
  21. * instance will be returned.
  22. *
  23. * You can optionally pass a {@link LoaderInterface} instance to the constructor.
  24. * Whenever a new metadata instance is created, it is passed to the loader,
  25. * which can configure the metadata based on configuration loaded from the
  26. * filesystem or a database. If you want to use multiple loaders, wrap them in a
  27. * {@link LoaderChain}.
  28. *
  29. * You can also optionally pass a {@link CacheInterface} instance to the
  30. * constructor. This cache will be used for persisting the generated metadata
  31. * between multiple PHP requests.
  32. *
  33. * @author Bernhard Schussek <bschussek@gmail.com>
  34. */
  35. class LazyLoadingMetadataFactory implements MetadataFactoryInterface
  36. {
  37. protected $loader;
  38. protected $cache;
  39. /**
  40. * The loaded metadata, indexed by class name.
  41. *
  42. * @var ClassMetadata[]
  43. */
  44. protected $loadedClasses = [];
  45. public function __construct(LoaderInterface $loader = null, CacheItemPoolInterface $cache = null)
  46. {
  47. $this->loader = $loader;
  48. $this->cache = $cache;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. *
  53. * If the method was called with the same class name (or an object of that
  54. * class) before, the same metadata instance is returned.
  55. *
  56. * If the factory was configured with a cache, this method will first look
  57. * for an existing metadata instance in the cache. If an existing instance
  58. * is found, it will be returned without further ado.
  59. *
  60. * Otherwise, a new metadata instance is created. If the factory was
  61. * configured with a loader, the metadata is passed to the
  62. * {@link LoaderInterface::loadClassMetadata()} method for further
  63. * configuration. At last, the new object is returned.
  64. */
  65. public function getMetadataFor($value)
  66. {
  67. if (!\is_object($value) && !\is_string($value)) {
  68. throw new NoSuchMetadataException(sprintf('Cannot create metadata for non-objects. Got: "%s".', get_debug_type($value)));
  69. }
  70. $class = ltrim(\is_object($value) ? \get_class($value) : $value, '\\');
  71. if (isset($this->loadedClasses[$class])) {
  72. return $this->loadedClasses[$class];
  73. }
  74. if (!class_exists($class) && !interface_exists($class, false)) {
  75. throw new NoSuchMetadataException(sprintf('The class or interface "%s" does not exist.', $class));
  76. }
  77. $cacheItem = null === $this->cache ? null : $this->cache->getItem($this->escapeClassName($class));
  78. if ($cacheItem && $cacheItem->isHit()) {
  79. $metadata = $cacheItem->get();
  80. // Include constraints from the parent class
  81. $this->mergeConstraints($metadata);
  82. return $this->loadedClasses[$class] = $metadata;
  83. }
  84. $metadata = new ClassMetadata($class);
  85. if (null !== $this->loader) {
  86. $this->loader->loadClassMetadata($metadata);
  87. }
  88. if (null !== $cacheItem) {
  89. $this->cache->save($cacheItem->set($metadata));
  90. }
  91. // Include constraints from the parent class
  92. $this->mergeConstraints($metadata);
  93. return $this->loadedClasses[$class] = $metadata;
  94. }
  95. private function mergeConstraints(ClassMetadata $metadata)
  96. {
  97. if ($metadata->getReflectionClass()->isInterface()) {
  98. return;
  99. }
  100. // Include constraints from the parent class
  101. if ($parent = $metadata->getReflectionClass()->getParentClass()) {
  102. $metadata->mergeConstraints($this->getMetadataFor($parent->name));
  103. }
  104. // Include constraints from all directly implemented interfaces
  105. foreach ($metadata->getReflectionClass()->getInterfaces() as $interface) {
  106. if ('Symfony\Component\Validator\GroupSequenceProviderInterface' === $interface->name) {
  107. continue;
  108. }
  109. if ($parent && \in_array($interface->getName(), $parent->getInterfaceNames(), true)) {
  110. continue;
  111. }
  112. $metadata->mergeConstraints($this->getMetadataFor($interface->name));
  113. }
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function hasMetadataFor($value)
  119. {
  120. if (!\is_object($value) && !\is_string($value)) {
  121. return false;
  122. }
  123. $class = ltrim(\is_object($value) ? \get_class($value) : $value, '\\');
  124. return class_exists($class) || interface_exists($class, false);
  125. }
  126. /**
  127. * Replaces backslashes by dots in a class name.
  128. */
  129. private function escapeClassName(string $class): string
  130. {
  131. if (false !== strpos($class, '@')) {
  132. // anonymous class: replace all PSR6-reserved characters
  133. return str_replace(["\0", '\\', '/', '@', ':', '{', '}', '(', ')'], '.', $class);
  134. }
  135. return str_replace('\\', '.', $class);
  136. }
  137. }