XmlFileLoader.php 14 KB

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