XmlFileLoader.php 14 KB

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