FileLoader.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. * @param string|string[]|null $exclude Glob patterns to exclude from the import
  45. */
  46. public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null/*, $exclude = null*/)
  47. {
  48. $args = \func_get_args();
  49. if ($ignoreNotFound = 'not_found' === $ignoreErrors) {
  50. $args[2] = false;
  51. } elseif (!\is_bool($ignoreErrors)) {
  52. @trigger_error(sprintf('Invalid argument $ignoreErrors provided to %s::import(): boolean or "not_found" expected, %s given.', static::class, \gettype($ignoreErrors)), \E_USER_DEPRECATED);
  53. $args[2] = (bool) $ignoreErrors;
  54. }
  55. try {
  56. parent::import(...$args);
  57. } catch (LoaderLoadException $e) {
  58. if (!$ignoreNotFound || !($prev = $e->getPrevious()) instanceof FileLocatorFileNotFoundException) {
  59. throw $e;
  60. }
  61. foreach ($prev->getTrace() as $frame) {
  62. if ('import' === ($frame['function'] ?? null) && is_a($frame['class'] ?? '', Loader::class, true)) {
  63. break;
  64. }
  65. }
  66. if (__FILE__ !== $frame['file']) {
  67. throw $e;
  68. }
  69. }
  70. }
  71. /**
  72. * Registers a set of classes as services using PSR-4 for discovery.
  73. *
  74. * @param Definition $prototype A definition to use as template
  75. * @param string $namespace The namespace prefix of classes in the scanned directory
  76. * @param string $resource The directory to look for classes, glob-patterns allowed
  77. * @param string|string[]|null $exclude A globbed path of files to exclude or an array of globbed paths of files to exclude
  78. */
  79. public function registerClasses(Definition $prototype, $namespace, $resource, $exclude = null)
  80. {
  81. if ('\\' !== substr($namespace, -1)) {
  82. throw new InvalidArgumentException(sprintf('Namespace prefix must end with a "\\": "%s".', $namespace));
  83. }
  84. if (!preg_match('/^(?:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+\\\\)++$/', $namespace)) {
  85. throw new InvalidArgumentException(sprintf('Namespace is not a valid PSR-4 prefix: "%s".', $namespace));
  86. }
  87. $classes = $this->findClasses($namespace, $resource, (array) $exclude);
  88. // prepare for deep cloning
  89. $serializedPrototype = serialize($prototype);
  90. foreach ($classes as $class => $errorMessage) {
  91. if (interface_exists($class, false)) {
  92. $this->interfaces[] = $class;
  93. } else {
  94. $this->setDefinition($class, $definition = unserialize($serializedPrototype));
  95. if (null !== $errorMessage) {
  96. $definition->addError($errorMessage);
  97. continue;
  98. }
  99. foreach (class_implements($class, false) as $interface) {
  100. $this->singlyImplemented[$interface] = ($this->singlyImplemented[$interface] ?? $class) !== $class ? false : $class;
  101. }
  102. }
  103. }
  104. if ($this->autoRegisterAliasesForSinglyImplementedInterfaces) {
  105. $this->registerAliasesForSinglyImplementedInterfaces();
  106. }
  107. }
  108. public function registerAliasesForSinglyImplementedInterfaces()
  109. {
  110. foreach ($this->interfaces as $interface) {
  111. if (!empty($this->singlyImplemented[$interface]) && !$this->container->has($interface)) {
  112. $this->container->setAlias($interface, $this->singlyImplemented[$interface])->setPublic(false);
  113. }
  114. }
  115. $this->interfaces = $this->singlyImplemented = [];
  116. }
  117. /**
  118. * Registers a definition in the container with its instanceof-conditionals.
  119. *
  120. * @param string $id
  121. */
  122. protected function setDefinition($id, Definition $definition)
  123. {
  124. $this->container->removeBindings($id);
  125. if ($this->isLoadingInstanceof) {
  126. if (!$definition instanceof ChildDefinition) {
  127. throw new InvalidArgumentException(sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', $id, \get_class($definition)));
  128. }
  129. $this->instanceof[$id] = $definition;
  130. } else {
  131. $this->container->setDefinition($id, $definition instanceof ChildDefinition ? $definition : $definition->setInstanceofConditionals($this->instanceof));
  132. }
  133. }
  134. private function findClasses(string $namespace, string $pattern, array $excludePatterns): array
  135. {
  136. $parameterBag = $this->container->getParameterBag();
  137. $excludePaths = [];
  138. $excludePrefix = null;
  139. $excludePatterns = $parameterBag->unescapeValue($parameterBag->resolveValue($excludePatterns));
  140. foreach ($excludePatterns as $excludePattern) {
  141. foreach ($this->glob($excludePattern, true, $resource, true, true) as $path => $info) {
  142. if (null === $excludePrefix) {
  143. $excludePrefix = $resource->getPrefix();
  144. }
  145. // normalize Windows slashes and remove trailing slashes
  146. $excludePaths[rtrim(str_replace('\\', '/', $path), '/')] = true;
  147. }
  148. }
  149. $pattern = $parameterBag->unescapeValue($parameterBag->resolveValue($pattern));
  150. $classes = [];
  151. $extRegexp = '/\\.php$/';
  152. $prefixLen = null;
  153. foreach ($this->glob($pattern, true, $resource, false, false, $excludePaths) as $path => $info) {
  154. if (null === $prefixLen) {
  155. $prefixLen = \strlen($resource->getPrefix());
  156. if ($excludePrefix && 0 !== strpos($excludePrefix, $resource->getPrefix())) {
  157. 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));
  158. }
  159. }
  160. if (isset($excludePaths[str_replace('\\', '/', $path)])) {
  161. continue;
  162. }
  163. if (!preg_match($extRegexp, $path, $m) || !$info->isReadable()) {
  164. continue;
  165. }
  166. $class = $namespace.ltrim(str_replace('/', '\\', substr($path, $prefixLen, -\strlen($m[0]))), '\\');
  167. 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)) {
  168. continue;
  169. }
  170. try {
  171. $r = $this->container->getReflectionClass($class);
  172. } catch (\ReflectionException $e) {
  173. $classes[$class] = $e->getMessage();
  174. continue;
  175. }
  176. // check to make sure the expected class exists
  177. if (!$r) {
  178. 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));
  179. }
  180. if ($r->isInstantiable() || $r->isInterface()) {
  181. $classes[$class] = null;
  182. }
  183. }
  184. // track only for new & removed files
  185. if ($resource instanceof GlobResource) {
  186. $this->container->addResource($resource);
  187. } else {
  188. foreach ($resource as $path) {
  189. $this->container->fileExists($path, false);
  190. }
  191. }
  192. return $classes;
  193. }
  194. }