XmlFileLoader.php 31 KB

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