XmlFileLoader.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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\Resource\FileResource;
  12. use Symfony\Component\Config\Util\XmlUtils;
  13. use Symfony\Component\DependencyInjection\Alias;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. use Symfony\Component\DependencyInjection\Definition;
  16. use Symfony\Component\DependencyInjection\DefinitionDecorator;
  17. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  18. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  19. use Symfony\Component\DependencyInjection\Reference;
  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->addResource(new FileResource($path));
  37. // anonymous services
  38. $this->processAnonymousServices($xml, $path);
  39. // imports
  40. $this->parseImports($xml, $path);
  41. // parameters
  42. $this->parseParameters($xml);
  43. // extensions
  44. $this->loadFromExtensions($xml);
  45. // services
  46. $this->parseDefinitions($xml, $path);
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function supports($resource, $type = null)
  52. {
  53. return \is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION);
  54. }
  55. /**
  56. * Parses parameters.
  57. *
  58. * @param \DOMDocument $xml
  59. */
  60. private function parseParameters(\DOMDocument $xml)
  61. {
  62. if ($parameters = $this->getChildren($xml->documentElement, 'parameters')) {
  63. $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter'));
  64. }
  65. }
  66. /**
  67. * Parses imports.
  68. *
  69. * @param \DOMDocument $xml
  70. * @param string $file
  71. */
  72. private function parseImports(\DOMDocument $xml, $file)
  73. {
  74. $xpath = new \DOMXPath($xml);
  75. $xpath->registerNamespace('container', self::NS);
  76. if (false === $imports = $xpath->query('//container:imports/container:import')) {
  77. return;
  78. }
  79. $defaultDirectory = \dirname($file);
  80. foreach ($imports as $import) {
  81. $this->setCurrentDir($defaultDirectory);
  82. $this->import($import->getAttribute('resource'), null, (bool) XmlUtils::phpize($import->getAttribute('ignore-errors')), $file);
  83. }
  84. }
  85. /**
  86. * Parses multiple definitions.
  87. *
  88. * @param \DOMDocument $xml
  89. * @param string $file
  90. */
  91. private function parseDefinitions(\DOMDocument $xml, $file)
  92. {
  93. $xpath = new \DOMXPath($xml);
  94. $xpath->registerNamespace('container', self::NS);
  95. if (false === $services = $xpath->query('//container:services/container:service')) {
  96. return;
  97. }
  98. foreach ($services as $service) {
  99. if (null !== $definition = $this->parseDefinition($service, $file)) {
  100. $this->container->setDefinition((string) $service->getAttribute('id'), $definition);
  101. }
  102. }
  103. }
  104. /**
  105. * Parses an individual Definition.
  106. *
  107. * @param \DOMElement $service
  108. * @param string $file
  109. *
  110. * @return Definition|null
  111. */
  112. private function parseDefinition(\DOMElement $service, $file)
  113. {
  114. if ($alias = $service->getAttribute('alias')) {
  115. $public = true;
  116. if ($publicAttr = $service->getAttribute('public')) {
  117. $public = XmlUtils::phpize($publicAttr);
  118. }
  119. $this->container->setAlias((string) $service->getAttribute('id'), new Alias($alias, $public));
  120. return;
  121. }
  122. if ($parent = $service->getAttribute('parent')) {
  123. $definition = new DefinitionDecorator($parent);
  124. } else {
  125. $definition = new Definition();
  126. }
  127. foreach (array('class', 'shared', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'lazy', 'abstract') as $key) {
  128. if ($value = $service->getAttribute($key)) {
  129. if (\in_array($key, array('factory-class', 'factory-method', 'factory-service'))) {
  130. @trigger_error(sprintf('The "%s" attribute of service "%s" in file "%s" is deprecated since Symfony 2.6 and will be removed in 3.0. Use the "factory" element instead.', $key, (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
  131. }
  132. $method = 'set'.str_replace('-', '', $key);
  133. $definition->$method(XmlUtils::phpize($value));
  134. }
  135. }
  136. if ($value = $service->getAttribute('autowire')) {
  137. $definition->setAutowired(XmlUtils::phpize($value));
  138. }
  139. if ($value = $service->getAttribute('scope')) {
  140. $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
  141. if ($triggerDeprecation) {
  142. @trigger_error(sprintf('The "scope" attribute of service "%s" in file "%s" is deprecated since Symfony 2.8 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
  143. }
  144. $definition->setScope(XmlUtils::phpize($value), false);
  145. }
  146. if ($value = $service->getAttribute('synchronized')) {
  147. $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
  148. if ($triggerDeprecation) {
  149. @trigger_error(sprintf('The "synchronized" attribute of service "%s" in file "%s" is deprecated since Symfony 2.7 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
  150. }
  151. $definition->setSynchronized(XmlUtils::phpize($value), $triggerDeprecation);
  152. }
  153. if ($files = $this->getChildren($service, 'file')) {
  154. $definition->setFile($files[0]->nodeValue);
  155. }
  156. if ($deprecated = $this->getChildren($service, 'deprecated')) {
  157. $definition->setDeprecated(true, $deprecated[0]->nodeValue ?: null);
  158. }
  159. $definition->setArguments($this->getArgumentsAsPhp($service, 'argument'));
  160. $definition->setProperties($this->getArgumentsAsPhp($service, 'property'));
  161. if ($factories = $this->getChildren($service, 'factory')) {
  162. $factory = $factories[0];
  163. if ($function = $factory->getAttribute('function')) {
  164. $definition->setFactory($function);
  165. } else {
  166. $factoryService = $this->getChildren($factory, 'service');
  167. if (isset($factoryService[0])) {
  168. $class = $this->parseDefinition($factoryService[0], $file);
  169. } elseif ($childService = $factory->getAttribute('service')) {
  170. $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
  171. } else {
  172. $class = $factory->getAttribute('class');
  173. }
  174. $definition->setFactory(array($class, $factory->getAttribute('method')));
  175. }
  176. }
  177. if ($configurators = $this->getChildren($service, 'configurator')) {
  178. $configurator = $configurators[0];
  179. if ($function = $configurator->getAttribute('function')) {
  180. $definition->setConfigurator($function);
  181. } else {
  182. $configuratorService = $this->getChildren($configurator, 'service');
  183. if (isset($configuratorService[0])) {
  184. $class = $this->parseDefinition($configuratorService[0], $file);
  185. } elseif ($childService = $configurator->getAttribute('service')) {
  186. $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
  187. } else {
  188. $class = $configurator->getAttribute('class');
  189. }
  190. $definition->setConfigurator(array($class, $configurator->getAttribute('method')));
  191. }
  192. }
  193. foreach ($this->getChildren($service, 'call') as $call) {
  194. $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument'));
  195. }
  196. foreach ($this->getChildren($service, 'tag') as $tag) {
  197. $parameters = array();
  198. foreach ($tag->attributes as $name => $node) {
  199. if ('name' === $name) {
  200. continue;
  201. }
  202. if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
  203. $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
  204. }
  205. // keep not normalized key for BC too
  206. $parameters[$name] = XmlUtils::phpize($node->nodeValue);
  207. }
  208. if ('' === $tag->getAttribute('name')) {
  209. throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $service->getAttribute('id'), $file));
  210. }
  211. $definition->addTag($tag->getAttribute('name'), $parameters);
  212. }
  213. foreach ($this->getChildren($service, 'autowiring-type') as $type) {
  214. $definition->addAutowiringType($type->textContent);
  215. }
  216. if ($value = $service->getAttribute('decorates')) {
  217. $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
  218. $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
  219. $definition->setDecoratedService($value, $renameId, $priority);
  220. }
  221. return $definition;
  222. }
  223. /**
  224. * Parses a XML file to a \DOMDocument.
  225. *
  226. * @param string $file Path to a file
  227. *
  228. * @return \DOMDocument
  229. *
  230. * @throws InvalidArgumentException When loading of XML file returns error
  231. */
  232. private function parseFileToDOM($file)
  233. {
  234. try {
  235. $dom = XmlUtils::loadFile($file, array($this, 'validateSchema'));
  236. } catch (\InvalidArgumentException $e) {
  237. throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e);
  238. }
  239. $this->validateExtensions($dom, $file);
  240. return $dom;
  241. }
  242. /**
  243. * Processes anonymous services.
  244. *
  245. * @param \DOMDocument $xml
  246. * @param string $file
  247. */
  248. private function processAnonymousServices(\DOMDocument $xml, $file)
  249. {
  250. $definitions = array();
  251. $count = 0;
  252. $xpath = new \DOMXPath($xml);
  253. $xpath->registerNamespace('container', self::NS);
  254. // anonymous services as arguments/properties
  255. if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) {
  256. foreach ($nodes as $node) {
  257. // give it a unique name
  258. $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
  259. $node->setAttribute('id', $id);
  260. if ($services = $this->getChildren($node, 'service')) {
  261. $definitions[$id] = array($services[0], $file, false);
  262. $services[0]->setAttribute('id', $id);
  263. // anonymous services are always private
  264. // we could not use the constant false here, because of XML parsing
  265. $services[0]->setAttribute('public', 'false');
  266. }
  267. }
  268. }
  269. // anonymous services "in the wild"
  270. if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) {
  271. foreach ($nodes as $node) {
  272. // give it a unique name
  273. $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
  274. $node->setAttribute('id', $id);
  275. $definitions[$id] = array($node, $file, true);
  276. }
  277. }
  278. // resolve definitions
  279. krsort($definitions);
  280. foreach ($definitions as $id => $def) {
  281. list($domElement, $file, $wild) = $def;
  282. if (null !== $definition = $this->parseDefinition($domElement, $file)) {
  283. $this->container->setDefinition($id, $definition);
  284. }
  285. if (true === $wild) {
  286. $tmpDomElement = new \DOMElement('_services', null, self::NS);
  287. $domElement->parentNode->replaceChild($tmpDomElement, $domElement);
  288. $tmpDomElement->setAttribute('id', $id);
  289. } else {
  290. if (null !== $domElement->parentNode) {
  291. $domElement->parentNode->removeChild($domElement);
  292. }
  293. }
  294. }
  295. }
  296. /**
  297. * Returns arguments as valid php types.
  298. *
  299. * @param \DOMElement $node
  300. * @param string $name
  301. * @param bool $lowercase
  302. *
  303. * @return mixed
  304. */
  305. private function getArgumentsAsPhp(\DOMElement $node, $name, $lowercase = true)
  306. {
  307. $arguments = array();
  308. foreach ($this->getChildren($node, $name) as $arg) {
  309. if ($arg->hasAttribute('name')) {
  310. $arg->setAttribute('key', $arg->getAttribute('name'));
  311. }
  312. // this is used by DefinitionDecorator to overwrite a specific
  313. // argument of the parent definition
  314. if ($arg->hasAttribute('index')) {
  315. $key = 'index_'.$arg->getAttribute('index');
  316. } elseif (!$arg->hasAttribute('key')) {
  317. // Append an empty argument, then fetch its key to overwrite it later
  318. $arguments[] = null;
  319. $keys = array_keys($arguments);
  320. $key = array_pop($keys);
  321. } else {
  322. $key = $arg->getAttribute('key');
  323. // parameter keys are case insensitive
  324. if ('parameter' == $name && $lowercase) {
  325. $key = strtolower($key);
  326. }
  327. }
  328. switch ($arg->getAttribute('type')) {
  329. case 'service':
  330. $onInvalid = $arg->getAttribute('on-invalid');
  331. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  332. if ('ignore' == $onInvalid) {
  333. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  334. } elseif ('null' == $onInvalid) {
  335. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  336. }
  337. if ($strict = $arg->getAttribute('strict')) {
  338. $strict = XmlUtils::phpize($strict);
  339. } else {
  340. $strict = true;
  341. }
  342. $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior, $strict);
  343. break;
  344. case 'expression':
  345. $arguments[$key] = new Expression($arg->nodeValue);
  346. break;
  347. case 'collection':
  348. $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, false);
  349. break;
  350. case 'string':
  351. $arguments[$key] = $arg->nodeValue;
  352. break;
  353. case 'constant':
  354. $arguments[$key] = \constant(trim($arg->nodeValue));
  355. break;
  356. default:
  357. $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
  358. }
  359. }
  360. return $arguments;
  361. }
  362. /**
  363. * Get child elements by name.
  364. *
  365. * @param \DOMNode $node
  366. * @param mixed $name
  367. *
  368. * @return array
  369. */
  370. private function getChildren(\DOMNode $node, $name)
  371. {
  372. $children = array();
  373. foreach ($node->childNodes as $child) {
  374. if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) {
  375. $children[] = $child;
  376. }
  377. }
  378. return $children;
  379. }
  380. /**
  381. * Validates a documents XML schema.
  382. *
  383. * @param \DOMDocument $dom
  384. *
  385. * @return bool
  386. *
  387. * @throws RuntimeException When extension references a non-existent XSD file
  388. */
  389. public function validateSchema(\DOMDocument $dom)
  390. {
  391. $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd'));
  392. if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
  393. $items = preg_split('/\s+/', $element);
  394. for ($i = 0, $nb = \count($items); $i < $nb; $i += 2) {
  395. if (!$this->container->hasExtension($items[$i])) {
  396. continue;
  397. }
  398. if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
  399. $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
  400. if (!is_file($path)) {
  401. throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', \get_class($extension), $path));
  402. }
  403. $schemaLocations[$items[$i]] = $path;
  404. }
  405. }
  406. }
  407. $tmpfiles = array();
  408. $imports = '';
  409. foreach ($schemaLocations as $namespace => $location) {
  410. $parts = explode('/', $location);
  411. $locationstart = 'file:///';
  412. if (0 === stripos($location, 'phar://')) {
  413. $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
  414. if ($tmpfile) {
  415. copy($location, $tmpfile);
  416. $tmpfiles[] = $tmpfile;
  417. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  418. } else {
  419. array_shift($parts);
  420. $locationstart = 'phar:///';
  421. }
  422. }
  423. $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  424. $location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
  425. $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
  426. }
  427. $source = <<<EOF
  428. <?xml version="1.0" encoding="utf-8" ?>
  429. <xsd:schema xmlns="http://symfony.com/schema"
  430. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  431. targetNamespace="http://symfony.com/schema"
  432. elementFormDefault="qualified">
  433. <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  434. $imports
  435. </xsd:schema>
  436. EOF
  437. ;
  438. $disableEntities = libxml_disable_entity_loader(false);
  439. $valid = @$dom->schemaValidateSource($source);
  440. libxml_disable_entity_loader($disableEntities);
  441. foreach ($tmpfiles as $tmpfile) {
  442. @unlink($tmpfile);
  443. }
  444. return $valid;
  445. }
  446. /**
  447. * Validates an extension.
  448. *
  449. * @param \DOMDocument $dom
  450. * @param string $file
  451. *
  452. * @throws InvalidArgumentException When no extension is found corresponding to a tag
  453. */
  454. private function validateExtensions(\DOMDocument $dom, $file)
  455. {
  456. foreach ($dom->documentElement->childNodes as $node) {
  457. if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
  458. continue;
  459. }
  460. // can it be handled by an extension?
  461. if (!$this->container->hasExtension($node->namespaceURI)) {
  462. $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
  463. 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 ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'));
  464. }
  465. }
  466. }
  467. /**
  468. * Loads from an extension.
  469. *
  470. * @param \DOMDocument $xml
  471. */
  472. private function loadFromExtensions(\DOMDocument $xml)
  473. {
  474. foreach ($xml->documentElement->childNodes as $node) {
  475. if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) {
  476. continue;
  477. }
  478. $values = static::convertDomElementToArray($node);
  479. if (!\is_array($values)) {
  480. $values = array();
  481. }
  482. $this->container->loadFromExtension($node->namespaceURI, $values);
  483. }
  484. }
  485. /**
  486. * Converts a \DOMElement object to a PHP array.
  487. *
  488. * The following rules applies during the conversion:
  489. *
  490. * * Each tag is converted to a key value or an array
  491. * if there is more than one "value"
  492. *
  493. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  494. * if the tag also has some nested tags
  495. *
  496. * * The attributes are converted to keys (<foo foo="bar"/>)
  497. *
  498. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  499. *
  500. * @param \DOMElement $element A \DOMElement instance
  501. *
  502. * @return array A PHP array
  503. */
  504. public static function convertDomElementToArray(\DOMElement $element)
  505. {
  506. return XmlUtils::convertDomElementToArray($element);
  507. }
  508. }