vendor/symfony/dependency-injection/Loader/XmlFileLoader.php line 230

Open in your IDE?
  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\Util\XmlUtils;
  12. use Symfony\Component\DependencyInjection\Alias;
  13. use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
  14. use Symfony\Component\DependencyInjection\Argument\BoundArgument;
  15. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  16. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  17. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  18. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
  19. use Symfony\Component\DependencyInjection\ChildDefinition;
  20. use Symfony\Component\DependencyInjection\ContainerBuilder;
  21. use Symfony\Component\DependencyInjection\ContainerInterface;
  22. use Symfony\Component\DependencyInjection\Definition;
  23. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  24. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  25. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  26. use Symfony\Component\DependencyInjection\Reference;
  27. use Symfony\Component\ExpressionLanguage\Expression;
  28. /**
  29. * XmlFileLoader loads XML files service definitions.
  30. *
  31. * @author Fabien Potencier <fabien@symfony.com>
  32. */
  33. class XmlFileLoader extends FileLoader
  34. {
  35. public const NS = 'http://symfony.com/schema/dic/services';
  36. protected $autoRegisterAliasesForSinglyImplementedInterfaces = false;
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function load($resource, string $type = null)
  41. {
  42. $path = $this->locator->locate($resource);
  43. $xml = $this->parseFileToDOM($path);
  44. $this->container->fileExists($path);
  45. $this->loadXml($xml, $path);
  46. if ($this->env) {
  47. $xpath = new \DOMXPath($xml);
  48. $xpath->registerNamespace('container', self::NS);
  49. foreach ($xpath->query(sprintf('//container:when[@env="%s"]', $this->env)) ?: [] as $root) {
  50. $env = $this->env;
  51. $this->env = null;
  52. try {
  53. $this->loadXml($xml, $path, $root);
  54. } finally {
  55. $this->env = $env;
  56. }
  57. }
  58. }
  59. return null;
  60. }
  61. private function loadXml(\DOMDocument $xml, string $path, \DOMNode $root = null): void
  62. {
  63. $defaults = $this->getServiceDefaults($xml, $path, $root);
  64. // anonymous services
  65. $this->processAnonymousServices($xml, $path, $root);
  66. // imports
  67. $this->parseImports($xml, $path, $root);
  68. // parameters
  69. $this->parseParameters($xml, $path, $root);
  70. // extensions
  71. $this->loadFromExtensions($xml, $root);
  72. // services
  73. try {
  74. $this->parseDefinitions($xml, $path, $defaults, $root);
  75. } finally {
  76. $this->instanceof = [];
  77. $this->registerAliasesForSinglyImplementedInterfaces();
  78. }
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public function supports($resource, string $type = null)
  84. {
  85. if (!\is_string($resource)) {
  86. return false;
  87. }
  88. if (null === $type && 'xml' === pathinfo($resource, \PATHINFO_EXTENSION)) {
  89. return true;
  90. }
  91. return 'xml' === $type;
  92. }
  93. private function parseParameters(\DOMDocument $xml, string $file, \DOMNode $root = null)
  94. {
  95. if ($parameters = $this->getChildren($root ?? $xml->documentElement, 'parameters')) {
  96. $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter', $file));
  97. }
  98. }
  99. private function parseImports(\DOMDocument $xml, string $file, \DOMNode $root = null)
  100. {
  101. $xpath = new \DOMXPath($xml);
  102. $xpath->registerNamespace('container', self::NS);
  103. if (false === $imports = $xpath->query('.//container:imports/container:import', $root)) {
  104. return;
  105. }
  106. $defaultDirectory = \dirname($file);
  107. foreach ($imports as $import) {
  108. $this->setCurrentDir($defaultDirectory);
  109. $this->import($import->getAttribute('resource'), XmlUtils::phpize($import->getAttribute('type')) ?: null, XmlUtils::phpize($import->getAttribute('ignore-errors')) ?: false, $file);
  110. }
  111. }
  112. private function parseDefinitions(\DOMDocument $xml, string $file, Definition $defaults, \DOMNode $root = null)
  113. {
  114. $xpath = new \DOMXPath($xml);
  115. $xpath->registerNamespace('container', self::NS);
  116. if (false === $services = $xpath->query('.//container:services/container:service|.//container:services/container:prototype|.//container:services/container:stack', $root)) {
  117. return;
  118. }
  119. $this->setCurrentDir(\dirname($file));
  120. $this->instanceof = [];
  121. $this->isLoadingInstanceof = true;
  122. $instanceof = $xpath->query('.//container:services/container:instanceof', $root);
  123. foreach ($instanceof as $service) {
  124. $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service, $file, new Definition()));
  125. }
  126. $this->isLoadingInstanceof = false;
  127. foreach ($services as $service) {
  128. if ('stack' === $service->tagName) {
  129. $service->setAttribute('parent', '-');
  130. $definition = $this->parseDefinition($service, $file, $defaults)
  131. ->setTags(array_merge_recursive(['container.stack' => [[]]], $defaults->getTags()))
  132. ;
  133. $this->setDefinition($id = (string) $service->getAttribute('id'), $definition);
  134. $stack = [];
  135. foreach ($this->getChildren($service, 'service') as $k => $frame) {
  136. $k = $frame->getAttribute('id') ?: $k;
  137. $frame->setAttribute('id', $id.'" at index "'.$k);
  138. if ($alias = $frame->getAttribute('alias')) {
  139. $this->validateAlias($frame, $file);
  140. $stack[$k] = new Reference($alias);
  141. } else {
  142. $stack[$k] = $this->parseDefinition($frame, $file, $defaults)
  143. ->setInstanceofConditionals($this->instanceof);
  144. }
  145. }
  146. $definition->setArguments($stack);
  147. } elseif (null !== $definition = $this->parseDefinition($service, $file, $defaults)) {
  148. if ('prototype' === $service->tagName) {
  149. $excludes = array_column($this->getChildren($service, 'exclude'), 'nodeValue');
  150. if ($service->hasAttribute('exclude')) {
  151. if (\count($excludes) > 0) {
  152. throw new InvalidArgumentException('You cannot use both the attribute "exclude" and <exclude> tags at the same time.');
  153. }
  154. $excludes = [$service->getAttribute('exclude')];
  155. }
  156. $this->registerClasses($definition, (string) $service->getAttribute('namespace'), (string) $service->getAttribute('resource'), $excludes);
  157. } else {
  158. $this->setDefinition((string) $service->getAttribute('id'), $definition);
  159. }
  160. }
  161. }
  162. }
  163. private function getServiceDefaults(\DOMDocument $xml, string $file, \DOMNode $root = null): Definition
  164. {
  165. $xpath = new \DOMXPath($xml);
  166. $xpath->registerNamespace('container', self::NS);
  167. if (null === $defaultsNode = $xpath->query('.//container:services/container:defaults', $root)->item(0)) {
  168. return new Definition();
  169. }
  170. $defaultsNode->setAttribute('id', '<defaults>');
  171. return $this->parseDefinition($defaultsNode, $file, new Definition());
  172. }
  173. /**
  174. * Parses an individual Definition.
  175. */
  176. private function parseDefinition(\DOMElement $service, string $file, Definition $defaults): ?Definition
  177. {
  178. if ($alias = $service->getAttribute('alias')) {
  179. $this->validateAlias($service, $file);
  180. $this->container->setAlias($service->getAttribute('id'), $alias = new Alias($alias));
  181. if ($publicAttr = $service->getAttribute('public')) {
  182. $alias->setPublic(XmlUtils::phpize($publicAttr));
  183. } elseif ($defaults->getChanges()['public'] ?? false) {
  184. $alias->setPublic($defaults->isPublic());
  185. }
  186. if ($deprecated = $this->getChildren($service, 'deprecated')) {
  187. $message = $deprecated[0]->nodeValue ?: '';
  188. $package = $deprecated[0]->getAttribute('package') ?: '';
  189. $version = $deprecated[0]->getAttribute('version') ?: '';
  190. if (!$deprecated[0]->hasAttribute('package')) {
  191. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "package" of the node "deprecated" in "%s" is deprecated.', $file);
  192. }
  193. if (!$deprecated[0]->hasAttribute('version')) {
  194. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "version" of the node "deprecated" in "%s" is deprecated.', $file);
  195. }
  196. $alias->setDeprecated($package, $version, $message);
  197. }
  198. return null;
  199. }
  200. if ($this->isLoadingInstanceof) {
  201. $definition = new ChildDefinition('');
  202. } elseif ($parent = $service->getAttribute('parent')) {
  203. $definition = new ChildDefinition($parent);
  204. } else {
  205. $definition = new Definition();
  206. }
  207. if ($defaults->getChanges()['public'] ?? false) {
  208. $definition->setPublic($defaults->isPublic());
  209. }
  210. $definition->setAutowired($defaults->isAutowired());
  211. $definition->setAutoconfigured($defaults->isAutoconfigured());
  212. $definition->setChanges([]);
  213. foreach (['class', 'public', 'shared', 'synthetic', 'abstract'] as $key) {
  214. if ($value = $service->getAttribute($key)) {
  215. $method = 'set'.$key;
  216. $definition->$method($value = XmlUtils::phpize($value));
  217. }
  218. }
  219. if ($value = $service->getAttribute('lazy')) {
  220. $definition->setLazy((bool) $value = XmlUtils::phpize($value));
  221. if (\is_string($value)) {
  222. $definition->addTag('proxy', ['interface' => $value]);
  223. }
  224. }
  225. if ($value = $service->getAttribute('autowire')) {
  226. $definition->setAutowired(XmlUtils::phpize($value));
  227. }
  228. if ($value = $service->getAttribute('autoconfigure')) {
  229. $definition->setAutoconfigured(XmlUtils::phpize($value));
  230. }
  231. if ($files = $this->getChildren($service, 'file')) {
  232. $definition->setFile($files[0]->nodeValue);
  233. }
  234. if ($deprecated = $this->getChildren($service, 'deprecated')) {
  235. $message = $deprecated[0]->nodeValue ?: '';
  236. $package = $deprecated[0]->getAttribute('package') ?: '';
  237. $version = $deprecated[0]->getAttribute('version') ?: '';
  238. if ('' === $package) {
  239. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "package" of the node "deprecated" in "%s" is deprecated.', $file);
  240. }
  241. if ('' === $version) {
  242. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "version" of the node "deprecated" in "%s" is deprecated.', $file);
  243. }
  244. $definition->setDeprecated($package, $version, $message);
  245. }
  246. $definition->setArguments($this->getArgumentsAsPhp($service, 'argument', $file, $definition instanceof ChildDefinition));
  247. $definition->setProperties($this->getArgumentsAsPhp($service, 'property', $file));
  248. if ($factories = $this->getChildren($service, 'factory')) {
  249. $factory = $factories[0];
  250. if ($function = $factory->getAttribute('function')) {
  251. $definition->setFactory($function);
  252. } else {
  253. if ($childService = $factory->getAttribute('service')) {
  254. $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
  255. } else {
  256. $class = $factory->hasAttribute('class') ? $factory->getAttribute('class') : null;
  257. }
  258. $definition->setFactory([$class, $factory->getAttribute('method') ?: '__invoke']);
  259. }
  260. }
  261. if ($configurators = $this->getChildren($service, 'configurator')) {
  262. $configurator = $configurators[0];
  263. if ($function = $configurator->getAttribute('function')) {
  264. $definition->setConfigurator($function);
  265. } else {
  266. if ($childService = $configurator->getAttribute('service')) {
  267. $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
  268. } else {
  269. $class = $configurator->getAttribute('class');
  270. }
  271. $definition->setConfigurator([$class, $configurator->getAttribute('method') ?: '__invoke']);
  272. }
  273. }
  274. foreach ($this->getChildren($service, 'call') as $call) {
  275. $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument', $file), XmlUtils::phpize($call->getAttribute('returns-clone')));
  276. }
  277. $tags = $this->getChildren($service, 'tag');
  278. foreach ($tags as $tag) {
  279. $parameters = [];
  280. $tagName = $tag->nodeValue;
  281. foreach ($tag->attributes as $name => $node) {
  282. if ('name' === $name && '' === $tagName) {
  283. continue;
  284. }
  285. if (str_contains($name, '-') && !str_contains($name, '_') && !\array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
  286. $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
  287. }
  288. // keep not normalized key
  289. $parameters[$name] = XmlUtils::phpize($node->nodeValue);
  290. }
  291. if ('' === $tagName && '' === $tagName = $tag->getAttribute('name')) {
  292. throw new InvalidArgumentException(sprintf('The tag name for service "%s" in "%s" must be a non-empty string.', $service->getAttribute('id'), $file));
  293. }
  294. $definition->addTag($tagName, $parameters);
  295. }
  296. $definition->setTags(array_merge_recursive($definition->getTags(), $defaults->getTags()));
  297. $bindings = $this->getArgumentsAsPhp($service, 'bind', $file);
  298. $bindingType = $this->isLoadingInstanceof ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING;
  299. foreach ($bindings as $argument => $value) {
  300. $bindings[$argument] = new BoundArgument($value, true, $bindingType, $file);
  301. }
  302. // deep clone, to avoid multiple process of the same instance in the passes
  303. $bindings = array_merge(unserialize(serialize($defaults->getBindings())), $bindings);
  304. if ($bindings) {
  305. $definition->setBindings($bindings);
  306. }
  307. if ($decorates = $service->getAttribute('decorates')) {
  308. $decorationOnInvalid = $service->getAttribute('decoration-on-invalid') ?: 'exception';
  309. if ('exception' === $decorationOnInvalid) {
  310. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  311. } elseif ('ignore' === $decorationOnInvalid) {
  312. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  313. } elseif ('null' === $decorationOnInvalid) {
  314. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  315. } else {
  316. throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration-on-invalid" on service "%s". Did you mean "exception", "ignore" or "null" in "%s"?', $decorationOnInvalid, $service->getAttribute('id'), $file));
  317. }
  318. $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
  319. $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
  320. $definition->setDecoratedService($decorates, $renameId, $priority, $invalidBehavior);
  321. }
  322. return $definition;
  323. }
  324. /**
  325. * Parses an XML file to a \DOMDocument.
  326. *
  327. * @throws InvalidArgumentException When loading of XML file returns error
  328. */
  329. private function parseFileToDOM(string $file): \DOMDocument
  330. {
  331. try {
  332. $dom = XmlUtils::loadFile($file, [$this, 'validateSchema']);
  333. } catch (\InvalidArgumentException $e) {
  334. throw new InvalidArgumentException(sprintf('Unable to parse file "%s": ', $file).$e->getMessage(), $e->getCode(), $e);
  335. }
  336. $this->validateExtensions($dom, $file);
  337. return $dom;
  338. }
  339. /**
  340. * Processes anonymous services.
  341. */
  342. private function processAnonymousServices(\DOMDocument $xml, string $file, \DOMNode $root = null)
  343. {
  344. $definitions = [];
  345. $count = 0;
  346. $suffix = '~'.ContainerBuilder::hash($file);
  347. $xpath = new \DOMXPath($xml);
  348. $xpath->registerNamespace('container', self::NS);
  349. // anonymous services as arguments/properties
  350. if (false !== $nodes = $xpath->query('.//container:argument[@type="service"][not(@id)]|.//container:property[@type="service"][not(@id)]|.//container:bind[not(@id)]|.//container:factory[not(@service)]|.//container:configurator[not(@service)]', $root)) {
  351. foreach ($nodes as $node) {
  352. if ($services = $this->getChildren($node, 'service')) {
  353. // give it a unique name
  354. $id = sprintf('.%d_%s', ++$count, preg_replace('/^.*\\\\/', '', $services[0]->getAttribute('class')).$suffix);
  355. $node->setAttribute('id', $id);
  356. $node->setAttribute('service', $id);
  357. $definitions[$id] = [$services[0], $file];
  358. $services[0]->setAttribute('id', $id);
  359. // anonymous services are always private
  360. // we could not use the constant false here, because of XML parsing
  361. $services[0]->setAttribute('public', 'false');
  362. }
  363. }
  364. }
  365. // anonymous services "in the wild"
  366. if (false !== $nodes = $xpath->query('.//container:services/container:service[not(@id)]', $root)) {
  367. foreach ($nodes as $node) {
  368. throw new InvalidArgumentException(sprintf('Top-level services must have "id" attribute, none found in "%s" at line %d.', $file, $node->getLineNo()));
  369. }
  370. }
  371. // resolve definitions
  372. uksort($definitions, 'strnatcmp');
  373. foreach (array_reverse($definitions) as $id => [$domElement, $file]) {
  374. if (null !== $definition = $this->parseDefinition($domElement, $file, new Definition())) {
  375. $this->setDefinition($id, $definition);
  376. }
  377. }
  378. }
  379. private function getArgumentsAsPhp(\DOMElement $node, string $name, string $file, bool $isChildDefinition = false): array
  380. {
  381. $arguments = [];
  382. foreach ($this->getChildren($node, $name) as $arg) {
  383. if ($arg->hasAttribute('name')) {
  384. $arg->setAttribute('key', $arg->getAttribute('name'));
  385. }
  386. // this is used by ChildDefinition to overwrite a specific
  387. // argument of the parent definition
  388. if ($arg->hasAttribute('index')) {
  389. $key = ($isChildDefinition ? 'index_' : '').$arg->getAttribute('index');
  390. } elseif (!$arg->hasAttribute('key')) {
  391. // Append an empty argument, then fetch its key to overwrite it later
  392. $arguments[] = null;
  393. $keys = array_keys($arguments);
  394. $key = array_pop($keys);
  395. } else {
  396. $key = $arg->getAttribute('key');
  397. }
  398. $onInvalid = $arg->getAttribute('on-invalid');
  399. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  400. if ('ignore' == $onInvalid) {
  401. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  402. } elseif ('ignore_uninitialized' == $onInvalid) {
  403. $invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
  404. } elseif ('null' == $onInvalid) {
  405. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  406. }
  407. switch ($arg->getAttribute('type')) {
  408. case 'service':
  409. if ('' === $arg->getAttribute('id')) {
  410. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".', $name, $file));
  411. }
  412. $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior);
  413. break;
  414. case 'expression':
  415. if (!class_exists(Expression::class)) {
  416. throw new \LogicException('The type="expression" attribute cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
  417. }
  418. $arguments[$key] = new Expression($arg->nodeValue);
  419. break;
  420. case 'collection':
  421. $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, $file);
  422. break;
  423. case 'iterator':
  424. $arg = $this->getArgumentsAsPhp($arg, $name, $file);
  425. try {
  426. $arguments[$key] = new IteratorArgument($arg);
  427. } catch (InvalidArgumentException $e) {
  428. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="iterator" only accepts collections of type="service" references in "%s".', $name, $file));
  429. }
  430. break;
  431. case 'service_closure':
  432. if ('' === $arg->getAttribute('id')) {
  433. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service_closure" has no or empty "id" attribute in "%s".', $name, $file));
  434. }
  435. $arguments[$key] = new ServiceClosureArgument(new Reference($arg->getAttribute('id'), $invalidBehavior));
  436. break;
  437. case 'service_locator':
  438. $arg = $this->getArgumentsAsPhp($arg, $name, $file);
  439. try {
  440. $arguments[$key] = new ServiceLocatorArgument($arg);
  441. } catch (InvalidArgumentException $e) {
  442. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service_locator" only accepts maps of type="service" references in "%s".', $name, $file));
  443. }
  444. break;
  445. case 'tagged':
  446. case 'tagged_iterator':
  447. case 'tagged_locator':
  448. $type = $arg->getAttribute('type');
  449. $forLocator = 'tagged_locator' === $type;
  450. if (!$arg->getAttribute('tag')) {
  451. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="%s" has no or empty "tag" attribute in "%s".', $name, $type, $file));
  452. }
  453. $arguments[$key] = new TaggedIteratorArgument($arg->getAttribute('tag'), $arg->getAttribute('index-by') ?: null, $arg->getAttribute('default-index-method') ?: null, $forLocator, $arg->getAttribute('default-priority-method') ?: null);
  454. if ($forLocator) {
  455. $arguments[$key] = new ServiceLocatorArgument($arguments[$key]);
  456. }
  457. break;
  458. case 'binary':
  459. if (false === $value = base64_decode($arg->nodeValue)) {
  460. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="binary" is not a valid base64 encoded string.', $name));
  461. }
  462. $arguments[$key] = $value;
  463. break;
  464. case 'abstract':
  465. $arguments[$key] = new AbstractArgument($arg->nodeValue);
  466. break;
  467. case 'string':
  468. $arguments[$key] = $arg->nodeValue;
  469. break;
  470. case 'constant':
  471. $arguments[$key] = \constant(trim($arg->nodeValue));
  472. break;
  473. default:
  474. $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
  475. }
  476. }
  477. return $arguments;
  478. }
  479. /**
  480. * Get child elements by name.
  481. *
  482. * @return \DOMElement[]
  483. */
  484. private function getChildren(\DOMNode $node, string $name): array
  485. {
  486. $children = [];
  487. foreach ($node->childNodes as $child) {
  488. if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) {
  489. $children[] = $child;
  490. }
  491. }
  492. return $children;
  493. }
  494. /**
  495. * Validates a documents XML schema.
  496. *
  497. * @return bool
  498. *
  499. * @throws RuntimeException When extension references a non-existent XSD file
  500. */
  501. public function validateSchema(\DOMDocument $dom)
  502. {
  503. $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')];
  504. if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
  505. $items = preg_split('/\s+/', $element);
  506. for ($i = 0, $nb = \count($items); $i < $nb; $i += 2) {
  507. if (!$this->container->hasExtension($items[$i])) {
  508. continue;
  509. }
  510. if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
  511. $ns = $extension->getNamespace();
  512. $path = str_replace([$ns, str_replace('http://', 'https://', $ns)], str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
  513. if (!is_file($path)) {
  514. throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s".', get_debug_type($extension), $path));
  515. }
  516. $schemaLocations[$items[$i]] = $path;
  517. }
  518. }
  519. }
  520. $tmpfiles = [];
  521. $imports = '';
  522. foreach ($schemaLocations as $namespace => $location) {
  523. $parts = explode('/', $location);
  524. $locationstart = 'file:///';
  525. if (0 === stripos($location, 'phar://')) {
  526. $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
  527. if ($tmpfile) {
  528. copy($location, $tmpfile);
  529. $tmpfiles[] = $tmpfile;
  530. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  531. } else {
  532. array_shift($parts);
  533. $locationstart = 'phar:///';
  534. }
  535. } elseif ('\\' === \DIRECTORY_SEPARATOR && str_starts_with($location, '\\\\')) {
  536. $locationstart = '';
  537. }
  538. $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  539. $location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
  540. $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
  541. }
  542. $source = <<<EOF
  543. <?xml version="1.0" encoding="utf-8" ?>
  544. <xsd:schema xmlns="http://symfony.com/schema"
  545. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  546. targetNamespace="http://symfony.com/schema"
  547. elementFormDefault="qualified">
  548. <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  549. $imports
  550. </xsd:schema>
  551. EOF
  552. ;
  553. if ($this->shouldEnableEntityLoader()) {
  554. $disableEntities = libxml_disable_entity_loader(false);
  555. $valid = @$dom->schemaValidateSource($source);
  556. libxml_disable_entity_loader($disableEntities);
  557. } else {
  558. $valid = @$dom->schemaValidateSource($source);
  559. }
  560. foreach ($tmpfiles as $tmpfile) {
  561. @unlink($tmpfile);
  562. }
  563. return $valid;
  564. }
  565. private function shouldEnableEntityLoader(): bool
  566. {
  567. // Version prior to 8.0 can be enabled without deprecation
  568. if (\PHP_VERSION_ID < 80000) {
  569. return true;
  570. }
  571. static $dom, $schema;
  572. if (null === $dom) {
  573. $dom = new \DOMDocument();
  574. $dom->loadXML('<?xml version="1.0"?><test/>');
  575. $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
  576. register_shutdown_function(static function () use ($tmpfile) {
  577. @unlink($tmpfile);
  578. });
  579. $schema = '<?xml version="1.0" encoding="utf-8"?>
  580. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  581. <xsd:include schemaLocation="file:///'.str_replace('\\', '/', $tmpfile).'" />
  582. </xsd:schema>';
  583. file_put_contents($tmpfile, '<?xml version="1.0" encoding="utf-8"?>
  584. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  585. <xsd:element name="test" type="testType" />
  586. <xsd:complexType name="testType"/>
  587. </xsd:schema>');
  588. }
  589. return !@$dom->schemaValidateSource($schema);
  590. }
  591. private function validateAlias(\DOMElement $alias, string $file)
  592. {
  593. foreach ($alias->attributes as $name => $node) {
  594. if (!\in_array($name, ['alias', 'id', 'public'])) {
  595. throw new InvalidArgumentException(sprintf('Invalid attribute "%s" defined for alias "%s" in "%s".', $name, $alias->getAttribute('id'), $file));
  596. }
  597. }
  598. foreach ($alias->childNodes as $child) {
  599. if (!$child instanceof \DOMElement || self::NS !== $child->namespaceURI) {
  600. continue;
  601. }
  602. if (!\in_array($child->localName, ['deprecated'], true)) {
  603. throw new InvalidArgumentException(sprintf('Invalid child element "%s" defined for alias "%s" in "%s".', $child->localName, $alias->getAttribute('id'), $file));
  604. }
  605. }
  606. }
  607. /**
  608. * Validates an extension.
  609. *
  610. * @throws InvalidArgumentException When no extension is found corresponding to a tag
  611. */
  612. private function validateExtensions(\DOMDocument $dom, string $file)
  613. {
  614. foreach ($dom->documentElement->childNodes as $node) {
  615. if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
  616. continue;
  617. }
  618. // can it be handled by an extension?
  619. if (!$this->container->hasExtension($node->namespaceURI)) {
  620. $extensionNamespaces = array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
  621. throw new InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in "%s"). Looked for namespace "%s", found "%s".', $node->tagName, $file, $node->namespaceURI, $extensionNamespaces ? implode('", "', $extensionNamespaces) : 'none'));
  622. }
  623. }
  624. }
  625. /**
  626. * Loads from an extension.
  627. */
  628. private function loadFromExtensions(\DOMDocument $xml)
  629. {
  630. foreach ($xml->documentElement->childNodes as $node) {
  631. if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) {
  632. continue;
  633. }
  634. $values = static::convertDomElementToArray($node);
  635. if (!\is_array($values)) {
  636. $values = [];
  637. }
  638. $this->container->loadFromExtension($node->namespaceURI, $values);
  639. }
  640. }
  641. /**
  642. * Converts a \DOMElement object to a PHP array.
  643. *
  644. * The following rules applies during the conversion:
  645. *
  646. * * Each tag is converted to a key value or an array
  647. * if there is more than one "value"
  648. *
  649. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  650. * if the tag also has some nested tags
  651. *
  652. * * The attributes are converted to keys (<foo foo="bar"/>)
  653. *
  654. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  655. *
  656. * @param \DOMElement $element A \DOMElement instance
  657. *
  658. * @return mixed
  659. */
  660. public static function convertDomElementToArray(\DOMElement $element)
  661. {
  662. return XmlUtils::convertDomElementToArray($element);
  663. }
  664. }