FileLoader.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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\DependencyInjection\Loader;
  11. use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException;
  12. use Symfony\Component\Config\Exception\LoaderLoadException;
  13. use Symfony\Component\Config\FileLocatorInterface;
  14. use Symfony\Component\Config\Loader\FileLoader as BaseFileLoader;
  15. use Symfony\Component\Config\Loader\Loader;
  16. use Symfony\Component\Config\Resource\GlobResource;
  17. use Symfony\Component\DependencyInjection\ChildDefinition;
  18. use Symfony\Component\DependencyInjection\ContainerBuilder;
  19. use Symfony\Component\DependencyInjection\Definition;
  20. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  21. /**
  22. * FileLoader is the abstract class used by all built-in loaders that are file based.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. */
  26. abstract class FileLoader extends BaseFileLoader
  27. {
  28. public const ANONYMOUS_ID_REGEXP = '/^\.\d+_[^~]*+~[._a-zA-Z\d]{7}$/';
  29. protected $container;
  30. protected $isLoadingInstanceof = false;
  31. protected $instanceof = [];
  32. protected $interfaces = [];
  33. protected $singlyImplemented = [];
  34. protected $autoRegisterAliasesForSinglyImplementedInterfaces = true;
  35. public function __construct(ContainerBuilder $container, FileLocatorInterface $locator)
  36. {
  37. $this->container = $container;
  38. parent::__construct($locator);
  39. }
  40. /**
  41. * {@inheritdoc}
  42. *
  43. * @param bool|string $ignoreErrors Whether errors should be ignored; pass "not_found" to ignore only when the loaded resource is not found
  44. */
  45. public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null, $exclude = null)
  46. {
  47. $args = \func_get_args();
  48. if ($ignoreNotFound = 'not_found' === $ignoreErrors) {
  49. $args[2] = false;
  50. } elseif (!\is_bool($ignoreErrors)) {
  51. throw new \TypeError(sprintf('Invalid argument $ignoreErrors provided to "%s::import()": boolean or "not_found" expected, "%s" given.', static::class, get_debug_type($ignoreErrors)));
  52. }
  53. try {
  54. parent::import(...$args);
  55. } catch (LoaderLoadException $e) {
  56. if (!$ignoreNotFound || !($prev = $e->getPrevious()) instanceof FileLocatorFileNotFoundException) {
  57. throw $e;
  58. }
  59. foreach ($prev->getTrace() as $frame) {
  60. if ('import' === ($frame['function'] ?? null) && is_a($frame['class'] ?? '', Loader::class, true)) {
  61. break;
  62. }
  63. }
  64. if (__FILE__ !== $frame['file']) {
  65. throw $e;
  66. }
  67. }
  68. }
  69. /**
  70. * Registers a set of classes as services using PSR-4 for discovery.
  71. *
  72. * @param Definition $prototype A definition to use as template
  73. * @param string $namespace The namespace prefix of classes in the scanned directory
  74. * @param string $resource The directory to look for classes, glob-patterns allowed
  75. * @param string|string[]|null $exclude A globbed path of files to exclude or an array of globbed paths of files to exclude
  76. */
  77. public function registerClasses(Definition $prototype, $namespace, $resource, $exclude = null)
  78. {
  79. if ('\\' !== substr($namespace, -1)) {
  80. throw new InvalidArgumentException(sprintf('Namespace prefix must end with a "\\": "%s".', $namespace));
  81. }
  82. if (!preg_match('/^(?:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+\\\\)++$/', $namespace)) {
  83. throw new InvalidArgumentException(sprintf('Namespace is not a valid PSR-4 prefix: "%s".', $namespace));
  84. }
  85. $classes = $this->findClasses($namespace, $resource, (array) $exclude);
  86. // prepare for deep cloning
  87. $serializedPrototype = serialize($prototype);
  88. foreach ($classes as $class => $errorMessage) {
  89. if (interface_exists($class, false)) {
  90. $this->interfaces[] = $class;
  91. } else {
  92. $this->setDefinition($class, $definition = unserialize($serializedPrototype));
  93. if (null !== $errorMessage) {
  94. $definition->addError($errorMessage);
  95. continue;
  96. }
  97. foreach (class_implements($class, false) as $interface) {
  98. $this->singlyImplemented[$interface] = ($this->singlyImplemented[$interface] ?? $class) !== $class ? false : $class;
  99. }
  100. }
  101. }
  102. if ($this->autoRegisterAliasesForSinglyImplementedInterfaces) {
  103. $this->registerAliasesForSinglyImplementedInterfaces();
  104. }
  105. }
  106. public function registerAliasesForSinglyImplementedInterfaces()
  107. {
  108. foreach ($this->interfaces as $interface) {
  109. if (!empty($this->singlyImplemented[$interface]) && !$this->container->has($interface)) {
  110. $this->container->setAlias($interface, $this->singlyImplemented[$interface]);
  111. }
  112. }
  113. $this->interfaces = $this->singlyImplemented = [];
  114. }
  115. /**
  116. * Registers a definition in the container with its instanceof-conditionals.
  117. *
  118. * @param string $id
  119. */
  120. protected function setDefinition($id, Definition $definition)
  121. {
  122. $this->container->removeBindings($id);
  123. if ($this->isLoadingInstanceof) {
  124. if (!$definition instanceof ChildDefinition) {
  125. throw new InvalidArgumentException(sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', $id, get_debug_type($definition)));
  126. }
  127. $this->instanceof[$id] = $definition;
  128. } else {
  129. $this->container->setDefinition($id, $definition->setInstanceofConditionals($this->instanceof));
  130. }
  131. }
  132. private function findClasses(string $namespace, string $pattern, array $excludePatterns): array
  133. {
  134. $parameterBag = $this->container->getParameterBag();
  135. $excludePaths = [];
  136. $excludePrefix = null;
  137. $excludePatterns = $parameterBag->unescapeValue($parameterBag->resolveValue($excludePatterns));
  138. foreach ($excludePatterns as $excludePattern) {
  139. foreach ($this->glob($excludePattern, true, $resource, true, true) as $path => $info) {
  140. if (null === $excludePrefix) {
  141. $excludePrefix = $resource->getPrefix();
  142. }
  143. // normalize Windows slashes
  144. $excludePaths[str_replace('\\', '/', $path)] = true;
  145. }
  146. }
  147. $pattern = $parameterBag->unescapeValue($parameterBag->resolveValue($pattern));
  148. $classes = [];
  149. $extRegexp = '/\\.php$/';
  150. $prefixLen = null;
  151. foreach ($this->glob($pattern, true, $resource, false, false, $excludePaths) as $path => $info) {
  152. if (null === $prefixLen) {
  153. $prefixLen = \strlen($resource->getPrefix());
  154. if ($excludePrefix && 0 !== strpos($excludePrefix, $resource->getPrefix())) {
  155. throw new InvalidArgumentException(sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern (%s) is a subset of the "resource" pattern (%s).', $namespace, $excludePattern, $pattern));
  156. }
  157. }
  158. if (isset($excludePaths[str_replace('\\', '/', $path)])) {
  159. continue;
  160. }
  161. if (!preg_match($extRegexp, $path, $m) || !$info->isReadable()) {
  162. continue;
  163. }
  164. $class = $namespace.ltrim(str_replace('/', '\\', substr($path, $prefixLen, -\strlen($m[0]))), '\\');
  165. if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $class)) {
  166. continue;
  167. }
  168. try {
  169. $r = $this->container->getReflectionClass($class);
  170. } catch (\ReflectionException $e) {
  171. $classes[$class] = $e->getMessage();
  172. continue;
  173. }
  174. // check to make sure the expected class exists
  175. if (!$r) {
  176. throw new InvalidArgumentException(sprintf('Expected to find class "%s" in file "%s" while importing services from resource "%s", but it was not found! Check the namespace prefix used with the resource.', $class, $path, $pattern));
  177. }
  178. if ($r->isInstantiable() || $r->isInterface()) {
  179. $classes[$class] = null;
  180. }
  181. }
  182. // track only for new & removed files
  183. if ($resource instanceof GlobResource) {
  184. $this->container->addResource($resource);
  185. } else {
  186. foreach ($resource as $path) {
  187. $this->container->fileExists($path, false);
  188. }
  189. }
  190. return $classes;
  191. }
  192. }