XmlFileLoader.php 27 KB

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