XmlFileLoader.php 30 KB

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