PageRenderTime 25ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php

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