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

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. $invalidSecurityElements = [];
  335. $errors = explode("\n", $e->getMessage());
  336. foreach ($errors as $i => $error) {
  337. if (preg_match("#^\[ERROR 1871] Element '\{http://symfony\.com/schema/dic/security}([^']+)'#", $error, $matches)) {
  338. $invalidSecurityElements[$i] = $matches[1];
  339. }
  340. }
  341. if ($invalidSecurityElements) {
  342. $dom = XmlUtils::loadFile($file);
  343. foreach ($invalidSecurityElements as $errorIndex => $tagName) {
  344. foreach ($dom->getElementsByTagNameNS('http://symfony.com/schema/dic/security', $tagName) as $element) {
  345. if (!$parent = $element->parentNode) {
  346. continue;
  347. }
  348. if ('http://symfony.com/schema/dic/security' !== $parent->namespaceURI) {
  349. continue;
  350. }
  351. if ('provider' === $parent->localName || 'firewall' === $parent->localName) {
  352. unset($errors[$errorIndex]);
  353. }
  354. }
  355. }
  356. }
  357. if ($errors) {
  358. throw new InvalidArgumentException(sprintf('Unable to parse file "%s": ', $file).implode("\n", $errors), $e->getCode(), $e);
  359. }
  360. }
  361. $this->validateExtensions($dom, $file);
  362. return $dom;
  363. }
  364. /**
  365. * Processes anonymous services.
  366. */
  367. private function processAnonymousServices(\DOMDocument $xml, string $file, ?\DOMNode $root = null)
  368. {
  369. $definitions = [];
  370. $count = 0;
  371. $suffix = '~'.ContainerBuilder::hash($file);
  372. $xpath = new \DOMXPath($xml);
  373. $xpath->registerNamespace('container', self::NS);
  374. // anonymous services as arguments/properties
  375. 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)) {
  376. foreach ($nodes as $node) {
  377. if ($services = $this->getChildren($node, 'service')) {
  378. // give it a unique name
  379. $id = sprintf('.%d_%s', ++$count, preg_replace('/^.*\\\\/', '', $services[0]->getAttribute('class')).$suffix);
  380. $node->setAttribute('id', $id);
  381. $node->setAttribute('service', $id);
  382. $definitions[$id] = [$services[0], $file];
  383. $services[0]->setAttribute('id', $id);
  384. // anonymous services are always private
  385. // we could not use the constant false here, because of XML parsing
  386. $services[0]->setAttribute('public', 'false');
  387. }
  388. }
  389. }
  390. // anonymous services "in the wild"
  391. if (false !== $nodes = $xpath->query('.//container:services/container:service[not(@id)]', $root)) {
  392. foreach ($nodes as $node) {
  393. throw new InvalidArgumentException(sprintf('Top-level services must have "id" attribute, none found in "%s" at line %d.', $file, $node->getLineNo()));
  394. }
  395. }
  396. // resolve definitions
  397. uksort($definitions, 'strnatcmp');
  398. foreach (array_reverse($definitions) as $id => [$domElement, $file]) {
  399. if (null !== $definition = $this->parseDefinition($domElement, $file, new Definition())) {
  400. $this->setDefinition($id, $definition);
  401. }
  402. }
  403. }
  404. private function getArgumentsAsPhp(\DOMElement $node, string $name, string $file, bool $isChildDefinition = false): array
  405. {
  406. $arguments = [];
  407. foreach ($this->getChildren($node, $name) as $arg) {
  408. if ($arg->hasAttribute('name')) {
  409. $arg->setAttribute('key', $arg->getAttribute('name'));
  410. }
  411. // this is used by ChildDefinition to overwrite a specific
  412. // argument of the parent definition
  413. if ($arg->hasAttribute('index')) {
  414. $key = ($isChildDefinition ? 'index_' : '').$arg->getAttribute('index');
  415. } elseif (!$arg->hasAttribute('key')) {
  416. // Append an empty argument, then fetch its key to overwrite it later
  417. $arguments[] = null;
  418. $keys = array_keys($arguments);
  419. $key = array_pop($keys);
  420. } else {
  421. $key = $arg->getAttribute('key');
  422. }
  423. $onInvalid = $arg->getAttribute('on-invalid');
  424. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  425. if ('ignore' == $onInvalid) {
  426. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  427. } elseif ('ignore_uninitialized' == $onInvalid) {
  428. $invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
  429. } elseif ('null' == $onInvalid) {
  430. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  431. }
  432. switch ($arg->getAttribute('type')) {
  433. case 'service':
  434. if ('' === $arg->getAttribute('id')) {
  435. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".', $name, $file));
  436. }
  437. $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior);
  438. break;
  439. case 'expression':
  440. if (!class_exists(Expression::class)) {
  441. throw new \LogicException('The type="expression" attribute cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
  442. }
  443. $arguments[$key] = new Expression($arg->nodeValue);
  444. break;
  445. case 'collection':
  446. $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, $file);
  447. break;
  448. case 'iterator':
  449. $arg = $this->getArgumentsAsPhp($arg, $name, $file);
  450. try {
  451. $arguments[$key] = new IteratorArgument($arg);
  452. } catch (InvalidArgumentException $e) {
  453. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="iterator" only accepts collections of type="service" references in "%s".', $name, $file));
  454. }
  455. break;
  456. case 'service_closure':
  457. if ('' === $arg->getAttribute('id')) {
  458. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service_closure" has no or empty "id" attribute in "%s".', $name, $file));
  459. }
  460. $arguments[$key] = new ServiceClosureArgument(new Reference($arg->getAttribute('id'), $invalidBehavior));
  461. break;
  462. case 'service_locator':
  463. $arg = $this->getArgumentsAsPhp($arg, $name, $file);
  464. try {
  465. $arguments[$key] = new ServiceLocatorArgument($arg);
  466. } catch (InvalidArgumentException $e) {
  467. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service_locator" only accepts maps of type="service" references in "%s".', $name, $file));
  468. }
  469. break;
  470. case 'tagged':
  471. case 'tagged_iterator':
  472. case 'tagged_locator':
  473. $type = $arg->getAttribute('type');
  474. $forLocator = 'tagged_locator' === $type;
  475. if (!$arg->getAttribute('tag')) {
  476. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="%s" has no or empty "tag" attribute in "%s".', $name, $type, $file));
  477. }
  478. $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);
  479. if ($forLocator) {
  480. $arguments[$key] = new ServiceLocatorArgument($arguments[$key]);
  481. }
  482. break;
  483. case 'binary':
  484. if (false === $value = base64_decode($arg->nodeValue)) {
  485. throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="binary" is not a valid base64 encoded string.', $name));
  486. }
  487. $arguments[$key] = $value;
  488. break;
  489. case 'abstract':
  490. $arguments[$key] = new AbstractArgument($arg->nodeValue);
  491. break;
  492. case 'string':
  493. $arguments[$key] = $arg->nodeValue;
  494. break;
  495. case 'constant':
  496. $arguments[$key] = \constant(trim($arg->nodeValue));
  497. break;
  498. default:
  499. $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
  500. }
  501. }
  502. return $arguments;
  503. }
  504. /**
  505. * Get child elements by name.
  506. *
  507. * @return \DOMElement[]
  508. */
  509. private function getChildren(\DOMNode $node, string $name): array
  510. {
  511. $children = [];
  512. foreach ($node->childNodes as $child) {
  513. if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) {
  514. $children[] = $child;
  515. }
  516. }
  517. return $children;
  518. }
  519. /**
  520. * Validates a documents XML schema.
  521. *
  522. * @return bool
  523. *
  524. * @throws RuntimeException When extension references a non-existent XSD file
  525. */
  526. public function validateSchema(\DOMDocument $dom)
  527. {
  528. $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')];
  529. if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
  530. $items = preg_split('/\s+/', $element);
  531. for ($i = 0, $nb = \count($items); $i < $nb; $i += 2) {
  532. if (!$this->container->hasExtension($items[$i])) {
  533. continue;
  534. }
  535. if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
  536. $ns = $extension->getNamespace();
  537. $path = str_replace([$ns, str_replace('http://', 'https://', $ns)], str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
  538. if (!is_file($path)) {
  539. throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s".', get_debug_type($extension), $path));
  540. }
  541. $schemaLocations[$items[$i]] = $path;
  542. }
  543. }
  544. }
  545. $tmpfiles = [];
  546. $imports = '';
  547. foreach ($schemaLocations as $namespace => $location) {
  548. $parts = explode('/', $location);
  549. $locationstart = 'file:///';
  550. if (0 === stripos($location, 'phar://')) {
  551. $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
  552. if ($tmpfile) {
  553. copy($location, $tmpfile);
  554. $tmpfiles[] = $tmpfile;
  555. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  556. } else {
  557. array_shift($parts);
  558. $locationstart = 'phar:///';
  559. }
  560. } elseif ('\\' === \DIRECTORY_SEPARATOR && str_starts_with($location, '\\\\')) {
  561. $locationstart = '';
  562. }
  563. $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  564. $location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
  565. $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
  566. }
  567. $source = <<<EOF
  568. <?xml version="1.0" encoding="utf-8" ?>
  569. <xsd:schema xmlns="http://symfony.com/schema"
  570. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  571. targetNamespace="http://symfony.com/schema"
  572. elementFormDefault="qualified">
  573. <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  574. $imports
  575. </xsd:schema>
  576. EOF
  577. ;
  578. if ($this->shouldEnableEntityLoader()) {
  579. $disableEntities = libxml_disable_entity_loader(false);
  580. $valid = @$dom->schemaValidateSource($source);
  581. libxml_disable_entity_loader($disableEntities);
  582. } else {
  583. $valid = @$dom->schemaValidateSource($source);
  584. }
  585. foreach ($tmpfiles as $tmpfile) {
  586. @unlink($tmpfile);
  587. }
  588. return $valid;
  589. }
  590. private function shouldEnableEntityLoader(): bool
  591. {
  592. // Version prior to 8.0 can be enabled without deprecation
  593. if (\PHP_VERSION_ID < 80000) {
  594. return true;
  595. }
  596. static $dom, $schema;
  597. if (null === $dom) {
  598. $dom = new \DOMDocument();
  599. $dom->loadXML('<?xml version="1.0"?><test/>');
  600. $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
  601. register_shutdown_function(static function () use ($tmpfile) {
  602. @unlink($tmpfile);
  603. });
  604. $schema = '<?xml version="1.0" encoding="utf-8"?>
  605. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  606. <xsd:include schemaLocation="file:///'.rawurlencode(str_replace('\\', '/', $tmpfile)).'" />
  607. </xsd:schema>';
  608. file_put_contents($tmpfile, '<?xml version="1.0" encoding="utf-8"?>
  609. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  610. <xsd:element name="test" type="testType" />
  611. <xsd:complexType name="testType"/>
  612. </xsd:schema>');
  613. }
  614. return !@$dom->schemaValidateSource($schema);
  615. }
  616. private function validateAlias(\DOMElement $alias, string $file)
  617. {
  618. foreach ($alias->attributes as $name => $node) {
  619. if (!\in_array($name, ['alias', 'id', 'public'])) {
  620. throw new InvalidArgumentException(sprintf('Invalid attribute "%s" defined for alias "%s" in "%s".', $name, $alias->getAttribute('id'), $file));
  621. }
  622. }
  623. foreach ($alias->childNodes as $child) {
  624. if (!$child instanceof \DOMElement || self::NS !== $child->namespaceURI) {
  625. continue;
  626. }
  627. if (!\in_array($child->localName, ['deprecated'], true)) {
  628. throw new InvalidArgumentException(sprintf('Invalid child element "%s" defined for alias "%s" in "%s".', $child->localName, $alias->getAttribute('id'), $file));
  629. }
  630. }
  631. }
  632. /**
  633. * Validates an extension.
  634. *
  635. * @throws InvalidArgumentException When no extension is found corresponding to a tag
  636. */
  637. private function validateExtensions(\DOMDocument $dom, string $file)
  638. {
  639. foreach ($dom->documentElement->childNodes as $node) {
  640. if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
  641. continue;
  642. }
  643. // can it be handled by an extension?
  644. if (!$this->container->hasExtension($node->namespaceURI)) {
  645. $extensionNamespaces = array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
  646. 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'));
  647. }
  648. }
  649. }
  650. /**
  651. * Loads from an extension.
  652. */
  653. private function loadFromExtensions(\DOMDocument $xml)
  654. {
  655. foreach ($xml->documentElement->childNodes as $node) {
  656. if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) {
  657. continue;
  658. }
  659. $values = static::convertDomElementToArray($node);
  660. if (!\is_array($values)) {
  661. $values = [];
  662. }
  663. $this->container->loadFromExtension($node->namespaceURI, $values);
  664. }
  665. }
  666. /**
  667. * Converts a \DOMElement object to a PHP array.
  668. *
  669. * The following rules applies during the conversion:
  670. *
  671. * * Each tag is converted to a key value or an array
  672. * if there is more than one "value"
  673. *
  674. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  675. * if the tag also has some nested tags
  676. *
  677. * * The attributes are converted to keys (<foo foo="bar"/>)
  678. *
  679. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  680. *
  681. * @param \DOMElement $element A \DOMElement instance
  682. *
  683. * @return mixed
  684. */
  685. public static function convertDomElementToArray(\DOMElement $element)
  686. {
  687. return XmlUtils::convertDomElementToArray($element, false);
  688. }
  689. }