XmlFileLoader.php 32 KB

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