XmlFileLoader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <?php
  2. namespace Symfony\Components\DependencyInjection\Loader;
  3. use Symfony\Components\DependencyInjection\Definition;
  4. use Symfony\Components\DependencyInjection\Reference;
  5. use Symfony\Components\DependencyInjection\BuilderConfiguration;
  6. use Symfony\Components\DependencyInjection\SimpleXMLElement;
  7. /*
  8. * This file is part of the symfony framework.
  9. *
  10. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  11. *
  12. * This source file is subject to the MIT license that is bundled
  13. * with this source code in the file LICENSE.
  14. */
  15. /**
  16. * XmlFileLoader loads XML files service definitions.
  17. *
  18. * @package symfony
  19. * @subpackage dependency_injection
  20. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  21. */
  22. class XmlFileLoader extends FileLoader
  23. {
  24. /**
  25. * Loads an array of XML files.
  26. *
  27. * @param string $file An XML file path
  28. *
  29. * @return BuilderConfiguration A BuilderConfiguration instance
  30. */
  31. public function load($file)
  32. {
  33. $configuration = new BuilderConfiguration();
  34. $xml = $this->loadFile($file);
  35. // anonymous services
  36. $xml = $this->processAnonymousServices($configuration, $xml, $file);
  37. // imports
  38. $this->parseImports($configuration, $xml, $file);
  39. // parameters
  40. $this->parseParameters($configuration, $xml, $file);
  41. // services
  42. $this->parseDefinitions($configuration, $xml, $file);
  43. // extensions
  44. $this->loadFromExtensions($configuration, $xml);
  45. return $configuration;
  46. }
  47. protected function parseParameters(BuilderConfiguration $configuration, $xml, $file)
  48. {
  49. if (!$xml->parameters)
  50. {
  51. return;
  52. }
  53. $configuration->addParameters($xml->parameters->getArgumentsAsPhp('parameter'));
  54. }
  55. protected function parseImports(BuilderConfiguration $configuration, $xml, $file)
  56. {
  57. if (!$xml->imports)
  58. {
  59. return;
  60. }
  61. foreach ($xml->imports->import as $import)
  62. {
  63. $configuration->merge($this->parseImport($import, $file));
  64. }
  65. }
  66. protected function parseImport($import, $file)
  67. {
  68. if (isset($import['class']) && $import['class'] !== get_class($this))
  69. {
  70. $class = (string) $import['class'];
  71. $loader = new $class($this->paths);
  72. }
  73. else
  74. {
  75. $loader = $this;
  76. }
  77. $importedFile = $this->getAbsolutePath((string) $import['resource'], dirname($file));
  78. return $loader->load($importedFile);
  79. }
  80. protected function parseDefinitions(BuilderConfiguration $configuration, $xml, $file)
  81. {
  82. if (!$xml->services)
  83. {
  84. return;
  85. }
  86. foreach ($xml->services->service as $service)
  87. {
  88. $this->parseDefinition($configuration, (string) $service['id'], $service, $file);
  89. }
  90. }
  91. protected function parseDefinition(BuilderConfiguration $configuration, $id, $service, $file)
  92. {
  93. if ((string) $service['alias'])
  94. {
  95. $configuration->setAlias($id, (string) $service['alias']);
  96. return;
  97. }
  98. $definition = new Definition((string) $service['class']);
  99. foreach (array('shared', 'constructor') as $key)
  100. {
  101. $method = 'set'.ucfirst($key);
  102. if (isset($service[$key]))
  103. {
  104. $definition->$method((string) $service->getAttributeAsPhp($key));
  105. }
  106. }
  107. if ($service->file)
  108. {
  109. $definition->setFile((string) $service->file);
  110. }
  111. $definition->setArguments($service->getArgumentsAsPhp('argument'));
  112. if (isset($service->configurator))
  113. {
  114. if (isset($service->configurator['function']))
  115. {
  116. $definition->setConfigurator((string) $service->configurator['function']);
  117. }
  118. else
  119. {
  120. if (isset($service->configurator['service']))
  121. {
  122. $class = new Reference((string) $service->configurator['service']);
  123. }
  124. else
  125. {
  126. $class = (string) $service->configurator['class'];
  127. }
  128. $definition->setConfigurator(array($class, (string) $service->configurator['method']));
  129. }
  130. }
  131. foreach ($service->call as $call)
  132. {
  133. $definition->addMethodCall((string) $call['method'], $call->getArgumentsAsPhp('argument'));
  134. }
  135. $configuration->setDefinition($id, $definition);
  136. }
  137. protected function loadFile($file)
  138. {
  139. $path = $this->getAbsolutePath($file);
  140. if (!file_exists($path))
  141. {
  142. throw new \InvalidArgumentException(sprintf('The service file "%s" does not exist (in: %s).', $file, implode(', ', $this->paths)));
  143. }
  144. $dom = new \DOMDocument();
  145. libxml_use_internal_errors(true);
  146. if (!$dom->load(realpath($path), LIBXML_COMPACT))
  147. {
  148. throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
  149. }
  150. $dom->validateOnParse = true;
  151. $dom->normalizeDocument();
  152. libxml_use_internal_errors(false);
  153. $this->validate($dom, $path);
  154. return simplexml_import_dom($dom, 'Symfony\\Components\\DependencyInjection\\SimpleXMLElement');
  155. }
  156. protected function processAnonymousServices(BuilderConfiguration $configuration, $xml, $file)
  157. {
  158. $definitions = array();
  159. $count = 0;
  160. // find anonymous service definitions
  161. $xml->registerXPathNamespace('container', 'http://www.symfony-project.org/schema/dic/services');
  162. $nodes = $xml->xpath('//container:argument[@type="service"][not(@id)]');
  163. foreach ($nodes as $node)
  164. {
  165. // give it a unique names
  166. $node['id'] = sprintf('_%s_%d', md5($file), ++$count);
  167. $definitions[(string) $node['id']] = array($node->service, $file);
  168. $node->service['id'] = (string) $node['id'];
  169. }
  170. // resolve definitions
  171. krsort($definitions);
  172. foreach ($definitions as $id => $def)
  173. {
  174. $this->parseDefinition($configuration, $id, $def[0], $def[1]);
  175. $oNode = dom_import_simplexml($def[0]);
  176. $oNode->parentNode->removeChild($oNode);
  177. }
  178. return $xml;
  179. }
  180. protected function validate($dom, $file)
  181. {
  182. $this->validateSchema($dom, $file);
  183. $this->validateExtensions($dom, $file);
  184. }
  185. protected function validateSchema($dom, $file)
  186. {
  187. $schemaLocations = array('http://www.symfony-project.org/schema/dic/services' => __DIR__.'/schema/dic/services/services-1.0.xsd');
  188. if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation'))
  189. {
  190. $items = preg_split('/\s+/', $element);
  191. for ($i = 0, $nb = count($items); $i < $nb; $i += 2)
  192. {
  193. $schemaLocations[$items[$i]] = str_replace('http://www.symfony-project.org/', __DIR__.'/', $items[$i + 1]);
  194. }
  195. }
  196. $imports = '';
  197. foreach ($schemaLocations as $namespace => $location)
  198. {
  199. $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
  200. }
  201. $source = <<<EOF
  202. <?xml version="1.0" encoding="utf-8" ?>
  203. <xsd:schema xmlns="http://www.symfony-project.org/schema"
  204. xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  205. targetNamespace="http://www.symfony-project.org/schema"
  206. elementFormDefault="qualified">
  207. <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  208. $imports
  209. </xsd:schema>
  210. EOF
  211. ;
  212. libxml_use_internal_errors(true);
  213. if (!$dom->schemaValidateSource($source))
  214. {
  215. throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
  216. }
  217. libxml_use_internal_errors(false);
  218. }
  219. protected function validateExtensions($dom, $file)
  220. {
  221. foreach ($dom->documentElement->childNodes as $node)
  222. {
  223. if (!$node instanceof \DOMElement || in_array($node->tagName, array('imports', 'parameters', 'services')))
  224. {
  225. continue;
  226. }
  227. if ($node->namespaceURI === 'http://www.symfony-project.org/schema/dic/services')
  228. {
  229. throw new \InvalidArgumentException(sprintf('The "%s" tag is not valid (in %s).', $node->tagName, $file));
  230. }
  231. // can it be handled by an extension?
  232. if (!static::getExtension($node->namespaceURI))
  233. {
  234. throw new \InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s).', $node->tagName, $file));
  235. }
  236. }
  237. }
  238. protected function getXmlErrors()
  239. {
  240. $errors = array();
  241. foreach (libxml_get_errors() as $error)
  242. {
  243. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  244. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  245. $error->code,
  246. trim($error->message),
  247. $error->file ? $error->file : 'n/a',
  248. $error->line,
  249. $error->column
  250. );
  251. }
  252. libxml_clear_errors();
  253. return $errors;
  254. }
  255. protected function loadFromExtensions(BuilderConfiguration $configuration, $xml)
  256. {
  257. foreach (dom_import_simplexml($xml)->childNodes as $node)
  258. {
  259. if (!$node instanceof \DOMElement || $node->namespaceURI === 'http://www.symfony-project.org/schema/dic/services')
  260. {
  261. continue;
  262. }
  263. $values = static::convertDomElementToArray($node);
  264. $config = $this->getExtension($node->namespaceURI)->load($node->localName, is_array($values) ? $values : array($values));
  265. $configuration->merge($config);
  266. }
  267. }
  268. /**
  269. * Converts a \DomElement object to a PHP array.
  270. *
  271. * The following rules applies during the conversion:
  272. *
  273. * * Each tag is converted to a key value or an array
  274. * if there is more than one "value"
  275. *
  276. * * The content of a tag is set under a "value" key (<foo>bar</foo>)
  277. * if the tag also has some nested tags
  278. *
  279. * * The attributes are converted to keys (<foo foo="bar"/>)
  280. *
  281. * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  282. *
  283. * @param \DomElement $element A \DomElement instance
  284. *
  285. * @return array A PHP array
  286. */
  287. static public function convertDomElementToArray(\DomElement $element)
  288. {
  289. $empty = true;
  290. $config = array();
  291. foreach ($element->attributes as $name => $node)
  292. {
  293. $config[$name] = SimpleXMLElement::phpize($node->value);
  294. $empty = false;
  295. }
  296. $nodeValue = false;
  297. foreach ($element->childNodes as $node)
  298. {
  299. if ($node instanceof \DOMText)
  300. {
  301. if (trim($node->nodeValue))
  302. {
  303. $nodeValue = trim($node->nodeValue);
  304. $empty = false;
  305. }
  306. }
  307. elseif (!$node instanceof \DOMComment)
  308. {
  309. if (isset($config[$node->localName]))
  310. {
  311. if (!is_array($config[$node->localName]))
  312. {
  313. $config[$node->localName] = array($config[$node->localName]);
  314. }
  315. $config[$node->localName][] = static::convertDomElementToArray($node);
  316. }
  317. else
  318. {
  319. $config[$node->localName] = static::convertDomElementToArray($node);
  320. }
  321. $empty = false;
  322. }
  323. }
  324. if (false !== $nodeValue)
  325. {
  326. $value = SimpleXMLElement::phpize($nodeValue);
  327. if (count($config))
  328. {
  329. $config['value'] = $value;
  330. }
  331. else
  332. {
  333. $config = $value;
  334. }
  335. }
  336. return !$empty ? $config : null;
  337. }
  338. }