XmlFileLoader.php 14 KB

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