XmlFileLoader.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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\DependencyInjection\DefinitionDecorator;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13. use Symfony\Component\DependencyInjection\Alias;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\DependencyInjection\Reference;
  16. use Symfony\Component\DependencyInjection\SimpleXMLElement;
  17. use Symfony\Component\Config\Resource\FileResource;
  18. /**
  19. * XmlFileLoader loads XML files service definitions.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class XmlFileLoader extends FileLoader
  24. {
  25. /**
  26. * Loads an XML file.
  27. *
  28. * @param mixed $file The resource
  29. * @param string $type The resource type
  30. */
  31. public function load($file, $type = null)
  32. {
  33. $path = $this->locator->locate($file);
  34. $xml = $this->parseFile($path);
  35. $xml->registerXPathNamespace('container', 'http://symfony.com/schema/dic/services');
  36. $this->container->addResource(new FileResource($path));
  37. // anonymous services
  38. $xml = $this->processAnonymousServices($xml, $path);
  39. // imports
  40. $this->parseImports($xml, $path);
  41. // parameters
  42. $this->parseParameters($xml, $path);
  43. // extensions
  44. $this->loadFromExtensions($xml);
  45. // services
  46. $this->parseDefinitions($xml, $path);
  47. }
  48. /**
  49. * Returns true if this class supports the given resource.
  50. *
  51. * @param mixed $resource A resource
  52. * @param string $type The resource type
  53. *
  54. * @return Boolean true if this class supports the given resource, false otherwise
  55. */
  56. public function supports($resource, $type = null)
  57. {
  58. return is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION);
  59. }
  60. /**
  61. * Parses parameters
  62. *
  63. * @param SimpleXMLElement $xml
  64. * @param string $file
  65. *
  66. * @return void
  67. */
  68. private function parseParameters(SimpleXMLElement $xml, $file)
  69. {
  70. if (!$xml->parameters) {
  71. return;
  72. }
  73. $this->container->getParameterBag()->add($xml->parameters->getArgumentsAsPhp('parameter'));
  74. }
  75. /**
  76. * Parses imports
  77. *
  78. * @param SimpleXMLElement $xml
  79. * @param string $file
  80. *
  81. * @return void
  82. */
  83. private function parseImports(SimpleXMLElement $xml, $file)
  84. {
  85. if (false === $imports = $xml->xpath('//container:imports/container:import')) {
  86. return;
  87. }
  88. foreach ($imports as $import) {
  89. $this->setCurrentDir(dirname($file));
  90. $this->import((string) $import['resource'], null, (Boolean) $import->getAttributeAsPhp('ignore-errors'), $file);
  91. }
  92. }
  93. /**
  94. * Parses multiple definitions
  95. *
  96. * @param SimpleXMLElement $xml
  97. * @param string $file
  98. *
  99. * @return void
  100. */
  101. private function parseDefinitions(SimpleXMLElement $xml, $file)
  102. {
  103. if (false === $services = $xml->xpath('//container:services/container:service')) {
  104. return;
  105. }
  106. foreach ($services as $service) {
  107. $this->parseDefinition((string) $service['id'], $service, $file);
  108. }
  109. }
  110. /**
  111. * Parses an individual Definition
  112. *
  113. * @param string $id
  114. * @param SimpleXMLElement $service
  115. * @param string $file
  116. *
  117. * @return void
  118. */
  119. private function parseDefinition($id, $service, $file)
  120. {
  121. if ((string) $service['alias']) {
  122. $public = true;
  123. if (isset($service['public'])) {
  124. $public = $service->getAttributeAsPhp('public');
  125. }
  126. $this->container->setAlias($id, new Alias((string) $service['alias'], $public));
  127. return;
  128. }
  129. if (isset($service['parent'])) {
  130. $definition = new DefinitionDecorator((string) $service['parent']);
  131. } else {
  132. $definition = new Definition();
  133. }
  134. foreach (array('class', 'scope', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'abstract') as $key) {
  135. if (isset($service[$key])) {
  136. $method = 'set'.str_replace('-', '', $key);
  137. $definition->$method((string) $service->getAttributeAsPhp($key));
  138. }
  139. }
  140. if ($service->file) {
  141. $definition->setFile((string) $service->file);
  142. }
  143. $definition->setArguments($service->getArgumentsAsPhp('argument'));
  144. $definition->setProperties($service->getArgumentsAsPhp('property'));
  145. if (isset($service->configurator)) {
  146. if (isset($service->configurator['function'])) {
  147. $definition->setConfigurator((string) $service->configurator['function']);
  148. } else {
  149. if (isset($service->configurator['service'])) {
  150. $class = new Reference((string) $service->configurator['service'], ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
  151. } else {
  152. $class = (string) $service->configurator['class'];
  153. }
  154. $definition->setConfigurator(array($class, (string) $service->configurator['method']));
  155. }
  156. }
  157. foreach ($service->call as $call) {
  158. $definition->addMethodCall((string) $call['method'], $call->getArgumentsAsPhp('argument'));
  159. }
  160. foreach ($service->tag as $tag) {
  161. $parameters = array();
  162. foreach ($tag->attributes() as $name => $value) {
  163. if ('name' === $name) {
  164. continue;
  165. }
  166. $parameters[$name] = SimpleXMLElement::phpize($value);
  167. }
  168. $definition->addTag((string) $tag['name'], $parameters);
  169. }
  170. $this->container->setDefinition($id, $definition);
  171. }
  172. /**
  173. * Parses a XML file.
  174. *
  175. * @param string $file Path to a file
  176. *
  177. * @throws \InvalidArgumentException When loading of XML file returns error
  178. */
  179. private function parseFile($file)
  180. {
  181. $internalErrors = libxml_use_internal_errors(true);
  182. $disableEntities = libxml_disable_entity_loader(true);
  183. libxml_clear_errors();
  184. $dom = new \DOMDocument();
  185. $dom->validateOnParse = true;
  186. if (!$dom->loadXML(file_get_contents($file), LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
  187. libxml_disable_entity_loader($disableEntities);
  188. throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors($internalErrors)));
  189. }
  190. $dom->normalizeDocument();
  191. libxml_use_internal_errors($internalErrors);
  192. libxml_disable_entity_loader($disableEntities);
  193. foreach ($dom->childNodes as $child) {
  194. if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
  195. throw new \InvalidArgumentException('Document types are not allowed.');
  196. }
  197. }
  198. $this->validate($dom, $file);
  199. return simplexml_import_dom($dom, 'Symfony\\Component\\DependencyInjection\\SimpleXMLElement');
  200. }
  201. /**
  202. * Processes anonymous services
  203. *
  204. * @param SimpleXMLElement $xml
  205. * @param string $file
  206. *
  207. * @return array An array of anonymous services
  208. */
  209. private function processAnonymousServices(SimpleXMLElement $xml, $file)
  210. {
  211. $definitions = array();
  212. $count = 0;
  213. // anonymous services as arguments
  214. if (false === $nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]')) {
  215. return $xml;
  216. }
  217. foreach ($nodes as $node) {
  218. // give it a unique name
  219. $node['id'] = sprintf('%s_%d', md5($file), ++$count);
  220. $definitions[(string) $node['id']] = array($node->service, $file, false);
  221. $node->service['id'] = (string) $node['id'];
  222. }
  223. // anonymous services "in the wild"
  224. if (false === $nodes = $xml->xpath('//container:services/container:service[not(@id)]')) {
  225. return $xml;
  226. }
  227. foreach ($nodes as $node) {
  228. // give it a unique name
  229. $node['id'] = sprintf('%s_%d', md5($file), ++$count);
  230. $definitions[(string) $node['id']] = array($node, $file, true);
  231. $node->service['id'] = (string) $node['id'];
  232. }
  233. // resolve definitions
  234. krsort($definitions);
  235. foreach ($definitions as $id => $def) {
  236. // anonymous services are always private
  237. $def[0]['public'] = false;
  238. $this->parseDefinition($id, $def[0], $def[1]);
  239. $oNode = dom_import_simplexml($def[0]);
  240. if (true === $def[2]) {
  241. $nNode = new \DOMElement('_services');
  242. $oNode->parentNode->replaceChild($nNode, $oNode);
  243. $nNode->setAttribute('id', $id);
  244. } else {
  245. $oNode->parentNode->removeChild($oNode);
  246. }
  247. }
  248. return $xml;
  249. }
  250. /**
  251. * Validates an XML document.
  252. *
  253. * @param DOMDocument $dom
  254. * @param string $file
  255. */
  256. private function validate(\DOMDocument $dom, $file)
  257. {
  258. $this->validateSchema($dom, $file);
  259. $this->validateExtensions($dom, $file);
  260. }
  261. /**
  262. * Validates a documents XML schema.
  263. *
  264. * @param \DOMDocument $dom
  265. * @param string $file
  266. *
  267. * @return void
  268. *
  269. * @throws \RuntimeException When extension references a non-existent XSD file
  270. * @throws \InvalidArgumentException When xml doesn't validate its xsd schema
  271. */
  272. private function validateSchema(\DOMDocument $dom, $file)
  273. {
  274. $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd'));
  275. if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
  276. $items = preg_split('/\s+/', $element);
  277. for ($i = 0, $nb = count($items); $i < $nb; $i += 2) {
  278. if (!$this->container->hasExtension($items[$i])) {
  279. continue;
  280. }
  281. if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
  282. $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
  283. if (!file_exists($path)) {
  284. throw new \RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path));
  285. }
  286. $schemaLocations[$items[$i]] = $path;
  287. }
  288. }
  289. }
  290. $tmpfiles = array();
  291. $imports = '';
  292. foreach ($schemaLocations as $namespace => $location) {
  293. $parts = explode('/', $location);
  294. if (0 === stripos($location, 'phar://')) {
  295. $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
  296. if ($tmpfile) {
  297. copy($location, $tmpfile);
  298. $tmpfiles[] = $tmpfile;
  299. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  300. }
  301. }
  302. $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  303. $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
  304. $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
  305. }
  306. $source = <<<EOF
  307. <?xml version="1.0" encoding="utf-8" ?>
  308. <xsd:schema xmlns="http://symfony.com/schema"
  309. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  310. targetNamespace="http://symfony.com/schema"
  311. elementFormDefault="qualified">
  312. <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  313. $imports
  314. </xsd:schema>
  315. EOF
  316. ;
  317. $current = libxml_use_internal_errors(true);
  318. libxml_clear_errors();
  319. $valid = $dom->schemaValidateSource($source);
  320. foreach ($tmpfiles as $tmpfile) {
  321. @unlink($tmpfile);
  322. }
  323. if (!$valid) {
  324. throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors($current)));
  325. }
  326. libxml_use_internal_errors($current);
  327. }
  328. /**
  329. * Validates an extension.
  330. *
  331. * @param \DOMDocument $dom
  332. * @param string $file
  333. *
  334. * @return void
  335. *
  336. * @throws \InvalidArgumentException When non valid tag are found or no extension are found
  337. */
  338. private function validateExtensions(\DOMDocument $dom, $file)
  339. {
  340. foreach ($dom->documentElement->childNodes as $node) {
  341. if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
  342. continue;
  343. }
  344. // can it be handled by an extension?
  345. if (!$this->container->hasExtension($node->namespaceURI)) {
  346. $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
  347. throw new \InvalidArgumentException(sprintf(
  348. 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
  349. $node->tagName,
  350. $file,
  351. $node->namespaceURI,
  352. $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
  353. ));
  354. }
  355. }
  356. }
  357. /**
  358. * Returns an array of XML errors.
  359. *
  360. * @return array
  361. */
  362. private function getXmlErrors($internalErrors)
  363. {
  364. $errors = array();
  365. foreach (libxml_get_errors() as $error) {
  366. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  367. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  368. $error->code,
  369. trim($error->message),
  370. $error->file ? $error->file : 'n/a',
  371. $error->line,
  372. $error->column
  373. );
  374. }
  375. libxml_clear_errors();
  376. libxml_use_internal_errors($internalErrors);
  377. return $errors;
  378. }
  379. /**
  380. * Loads from an extension.
  381. *
  382. * @param SimpleXMLElement $xml
  383. *
  384. * @return void
  385. */
  386. private function loadFromExtensions(SimpleXMLElement $xml)
  387. {
  388. foreach (dom_import_simplexml($xml)->childNodes as $node) {
  389. if (!$node instanceof \DOMElement || $node->namespaceURI === 'http://symfony.com/schema/dic/services') {
  390. continue;
  391. }
  392. $values = static::convertDomElementToArray($node);
  393. if (!is_array($values)) {
  394. $values = array();
  395. }
  396. $this->container->loadFromExtension($node->namespaceURI, $values);
  397. }
  398. }
  399. /**
  400. * Converts a \DomElement object to a PHP array.
  401. *
  402. * The following rules applies during the conversion:
  403. *
  404. * * Each tag is converted to a key value or an array
  405. * if there is more than one "value"
  406. *
  407. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  408. * if the tag also has some nested tags
  409. *
  410. * * The attributes are converted to keys (<foo foo="bar"/>)
  411. *
  412. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  413. *
  414. * @param \DomElement $element A \DomElement instance
  415. *
  416. * @return array A PHP array
  417. */
  418. public static function convertDomElementToArray(\DomElement $element)
  419. {
  420. $empty = true;
  421. $config = array();
  422. foreach ($element->attributes as $name => $node) {
  423. $config[$name] = SimpleXMLElement::phpize($node->value);
  424. $empty = false;
  425. }
  426. $nodeValue = false;
  427. foreach ($element->childNodes as $node) {
  428. if ($node instanceof \DOMText) {
  429. if (trim($node->nodeValue)) {
  430. $nodeValue = trim($node->nodeValue);
  431. $empty = false;
  432. }
  433. } elseif (!$node instanceof \DOMComment) {
  434. if ($node instanceof \DOMElement && '_services' === $node->nodeName) {
  435. $value = new Reference($node->getAttribute('id'));
  436. } else {
  437. $value = static::convertDomElementToArray($node);
  438. }
  439. $key = $node->localName;
  440. if (isset($config[$key])) {
  441. if (!is_array($config[$key]) || !is_int(key($config[$key]))) {
  442. $config[$key] = array($config[$key]);
  443. }
  444. $config[$key][] = $value;
  445. } else {
  446. $config[$key] = $value;
  447. }
  448. $empty = false;
  449. }
  450. }
  451. if (false !== $nodeValue) {
  452. $value = SimpleXMLElement::phpize($nodeValue);
  453. if (count($config)) {
  454. $config['value'] = $value;
  455. } else {
  456. $config = $value;
  457. }
  458. }
  459. return !$empty ? $config : null;
  460. }
  461. }