XmlFileLoader.php 11 KB

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