4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\Loader;
14 use Symfony\Component\Config\Resource\FileResource;
15 use Symfony\Component\Config\Util\XmlUtils;
16 use Symfony\Component\DependencyInjection\DefinitionDecorator;
17 use Symfony\Component\DependencyInjection\ContainerInterface;
18 use Symfony\Component\DependencyInjection\Alias;
19 use Symfony\Component\DependencyInjection\Definition;
20 use Symfony\Component\DependencyInjection\Reference;
21 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
22 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
23 use Symfony\Component\ExpressionLanguage\Expression;
26 * XmlFileLoader loads XML files service definitions.
28 * @author Fabien Potencier <fabien@symfony.com>
30 class XmlFileLoader extends FileLoader
32 const NS = 'http://symfony.com/schema/dic/services';
37 public function load($resource, $type = null)
39 $path = $this->locator->locate($resource);
41 $xml = $this->parseFileToDOM($path);
43 $this->container->addResource(new FileResource($path));
46 $this->processAnonymousServices($xml, $path);
49 $this->parseImports($xml, $path);
52 $this->parseParameters($xml);
55 $this->loadFromExtensions($xml);
58 $this->parseDefinitions($xml, $path);
64 public function supports($resource, $type = null)
66 return is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION);
72 * @param \DOMDocument $xml
74 private function parseParameters(\DOMDocument $xml)
76 if ($parameters = $this->getChildren($xml->documentElement, 'parameters')) {
77 $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter'));
84 * @param \DOMDocument $xml
87 private function parseImports(\DOMDocument $xml, $file)
89 $xpath = new \DOMXPath($xml);
90 $xpath->registerNamespace('container', self::NS);
92 if (false === $imports = $xpath->query('//container:imports/container:import')) {
96 $defaultDirectory = dirname($file);
97 foreach ($imports as $import) {
98 $this->setCurrentDir($defaultDirectory);
99 $this->import($import->getAttribute('resource'), null, (bool) XmlUtils::phpize($import->getAttribute('ignore-errors')), $file);
104 * Parses multiple definitions.
106 * @param \DOMDocument $xml
107 * @param string $file
109 private function parseDefinitions(\DOMDocument $xml, $file)
111 $xpath = new \DOMXPath($xml);
112 $xpath->registerNamespace('container', self::NS);
114 if (false === $services = $xpath->query('//container:services/container:service')) {
118 foreach ($services as $service) {
119 if (null !== $definition = $this->parseDefinition($service, $file)) {
120 $this->container->setDefinition((string) $service->getAttribute('id'), $definition);
126 * Parses an individual Definition.
128 * @param \DOMElement $service
129 * @param string $file
131 * @return Definition|null
133 private function parseDefinition(\DOMElement $service, $file)
135 if ($alias = $service->getAttribute('alias')) {
136 $this->validateAlias($service, $file);
139 if ($publicAttr = $service->getAttribute('public')) {
140 $public = XmlUtils::phpize($publicAttr);
142 $this->container->setAlias((string) $service->getAttribute('id'), new Alias($alias, $public));
147 if ($parent = $service->getAttribute('parent')) {
148 $definition = new DefinitionDecorator($parent);
150 $definition = new Definition();
153 foreach (array('class', 'shared', 'public', 'synthetic', 'lazy', 'abstract') as $key) {
154 if ($value = $service->getAttribute($key)) {
155 $method = 'set'.$key;
156 $definition->$method(XmlUtils::phpize($value));
160 if ($value = $service->getAttribute('autowire')) {
161 $definition->setAutowired(XmlUtils::phpize($value));
164 if ($files = $this->getChildren($service, 'file')) {
165 $definition->setFile($files[0]->nodeValue);
168 if ($deprecated = $this->getChildren($service, 'deprecated')) {
169 $definition->setDeprecated(true, $deprecated[0]->nodeValue ?: null);
172 $definition->setArguments($this->getArgumentsAsPhp($service, 'argument'));
173 $definition->setProperties($this->getArgumentsAsPhp($service, 'property'));
175 if ($factories = $this->getChildren($service, 'factory')) {
176 $factory = $factories[0];
177 if ($function = $factory->getAttribute('function')) {
178 $definition->setFactory($function);
180 $factoryService = $this->getChildren($factory, 'service');
182 if (isset($factoryService[0])) {
183 $class = $this->parseDefinition($factoryService[0], $file);
184 } elseif ($childService = $factory->getAttribute('service')) {
185 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
187 $class = $factory->getAttribute('class');
190 $definition->setFactory(array($class, $factory->getAttribute('method')));
194 if ($configurators = $this->getChildren($service, 'configurator')) {
195 $configurator = $configurators[0];
196 if ($function = $configurator->getAttribute('function')) {
197 $definition->setConfigurator($function);
199 $configuratorService = $this->getChildren($configurator, 'service');
201 if (isset($configuratorService[0])) {
202 $class = $this->parseDefinition($configuratorService[0], $file);
203 } elseif ($childService = $configurator->getAttribute('service')) {
204 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
206 $class = $configurator->getAttribute('class');
209 $definition->setConfigurator(array($class, $configurator->getAttribute('method')));
213 foreach ($this->getChildren($service, 'call') as $call) {
214 $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument'));
217 foreach ($this->getChildren($service, 'tag') as $tag) {
218 $parameters = array();
219 foreach ($tag->attributes as $name => $node) {
220 if ('name' === $name) {
224 if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
225 $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
227 // keep not normalized key
228 $parameters[$name] = XmlUtils::phpize($node->nodeValue);
231 if ('' === $tag->getAttribute('name')) {
232 throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $service->getAttribute('id'), $file));
235 $definition->addTag($tag->getAttribute('name'), $parameters);
238 foreach ($this->getChildren($service, 'autowiring-type') as $type) {
239 $definition->addAutowiringType($type->textContent);
242 if ($value = $service->getAttribute('decorates')) {
243 $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
244 $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
245 $definition->setDecoratedService($value, $renameId, $priority);
252 * Parses a XML file to a \DOMDocument.
254 * @param string $file Path to a file
256 * @return \DOMDocument
258 * @throws InvalidArgumentException When loading of XML file returns error
260 private function parseFileToDOM($file)
263 $dom = XmlUtils::loadFile($file, array($this, 'validateSchema'));
264 } catch (\InvalidArgumentException $e) {
265 throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e);
268 $this->validateExtensions($dom, $file);
274 * Processes anonymous services.
276 * @param \DOMDocument $xml
277 * @param string $file
279 private function processAnonymousServices(\DOMDocument $xml, $file)
281 $definitions = array();
284 $xpath = new \DOMXPath($xml);
285 $xpath->registerNamespace('container', self::NS);
287 // anonymous services as arguments/properties
288 if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) {
289 foreach ($nodes as $node) {
290 // give it a unique name
291 $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
292 $node->setAttribute('id', $id);
294 if ($services = $this->getChildren($node, 'service')) {
295 $definitions[$id] = array($services[0], $file, false);
296 $services[0]->setAttribute('id', $id);
298 // anonymous services are always private
299 // we could not use the constant false here, because of XML parsing
300 $services[0]->setAttribute('public', 'false');
305 // anonymous services "in the wild"
306 if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) {
307 foreach ($nodes as $node) {
308 // give it a unique name
309 $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
310 $node->setAttribute('id', $id);
311 $definitions[$id] = array($node, $file, true);
315 // resolve definitions
316 krsort($definitions);
317 foreach ($definitions as $id => list($domElement, $file, $wild)) {
318 if (null !== $definition = $this->parseDefinition($domElement, $file)) {
319 $this->container->setDefinition($id, $definition);
322 if (true === $wild) {
323 $tmpDomElement = new \DOMElement('_services', null, self::NS);
324 $domElement->parentNode->replaceChild($tmpDomElement, $domElement);
325 $tmpDomElement->setAttribute('id', $id);
327 $domElement->parentNode->removeChild($domElement);
333 * Returns arguments as valid php types.
335 * @param \DOMElement $node
336 * @param string $name
337 * @param bool $lowercase
341 private function getArgumentsAsPhp(\DOMElement $node, $name, $lowercase = true)
343 $arguments = array();
344 foreach ($this->getChildren($node, $name) as $arg) {
345 if ($arg->hasAttribute('name')) {
346 $arg->setAttribute('key', $arg->getAttribute('name'));
349 // this is used by DefinitionDecorator to overwrite a specific
350 // argument of the parent definition
351 if ($arg->hasAttribute('index')) {
352 $key = 'index_'.$arg->getAttribute('index');
353 } elseif (!$arg->hasAttribute('key')) {
354 // Append an empty argument, then fetch its key to overwrite it later
356 $keys = array_keys($arguments);
357 $key = array_pop($keys);
359 $key = $arg->getAttribute('key');
361 // parameter keys are case insensitive
362 if ('parameter' == $name && $lowercase) {
363 $key = strtolower($key);
367 switch ($arg->getAttribute('type')) {
369 $onInvalid = $arg->getAttribute('on-invalid');
370 $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
371 if ('ignore' == $onInvalid) {
372 $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
373 } elseif ('null' == $onInvalid) {
374 $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
377 $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior);
380 $arguments[$key] = new Expression($arg->nodeValue);
383 $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, false);
386 $arguments[$key] = $arg->nodeValue;
389 $arguments[$key] = constant(trim($arg->nodeValue));
392 $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
400 * Get child elements by name.
402 * @param \DOMNode $node
407 private function getChildren(\DOMNode $node, $name)
410 foreach ($node->childNodes as $child) {
411 if ($child instanceof \DOMElement && $child->localName === $name && $child->namespaceURI === self::NS) {
412 $children[] = $child;
420 * Validates a documents XML schema.
422 * @param \DOMDocument $dom
426 * @throws RuntimeException When extension references a non-existent XSD file
428 public function validateSchema(\DOMDocument $dom)
430 $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd'));
432 if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
433 $items = preg_split('/\s+/', $element);
434 for ($i = 0, $nb = count($items); $i < $nb; $i += 2) {
435 if (!$this->container->hasExtension($items[$i])) {
439 if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
440 $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
442 if (!is_file($path)) {
443 throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path));
446 $schemaLocations[$items[$i]] = $path;
453 foreach ($schemaLocations as $namespace => $location) {
454 $parts = explode('/', $location);
455 if (0 === stripos($location, 'phar://')) {
456 $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
458 copy($location, $tmpfile);
459 $tmpfiles[] = $tmpfile;
460 $parts = explode('/', str_replace('\\', '/', $tmpfile));
463 $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
464 $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
466 $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
470 <?xml version="1.0" encoding="utf-8" ?>
471 <xsd:schema xmlns="http://symfony.com/schema"
472 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
473 targetNamespace="http://symfony.com/schema"
474 elementFormDefault="qualified">
476 <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
482 $disableEntities = libxml_disable_entity_loader(false);
483 $valid = @$dom->schemaValidateSource($source);
484 libxml_disable_entity_loader($disableEntities);
486 foreach ($tmpfiles as $tmpfile) {
494 * Validates an alias.
496 * @param \DOMElement $alias
497 * @param string $file
499 private function validateAlias(\DOMElement $alias, $file)
501 foreach ($alias->attributes as $name => $node) {
502 if (!in_array($name, array('alias', 'id', 'public'))) {
503 @trigger_error(sprintf('Using the attribute "%s" is deprecated for the service "%s" which is defined as an alias in "%s". Allowed attributes for service aliases are "alias", "id" and "public". The XmlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported attributes.', $name, $alias->getAttribute('id'), $file), E_USER_DEPRECATED);
507 foreach ($alias->childNodes as $child) {
508 if ($child instanceof \DOMElement && $child->namespaceURI === self::NS) {
509 @trigger_error(sprintf('Using the element "%s" is deprecated for the service "%s" which is defined as an alias in "%s". The XmlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported elements.', $child->localName, $alias->getAttribute('id'), $file), E_USER_DEPRECATED);
515 * Validates an extension.
517 * @param \DOMDocument $dom
518 * @param string $file
520 * @throws InvalidArgumentException When no extension is found corresponding to a tag
522 private function validateExtensions(\DOMDocument $dom, $file)
524 foreach ($dom->documentElement->childNodes as $node) {
525 if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
529 // can it be handled by an extension?
530 if (!$this->container->hasExtension($node->namespaceURI)) {
531 $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
532 throw new InvalidArgumentException(sprintf(
533 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
537 $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
544 * Loads from an extension.
546 * @param \DOMDocument $xml
548 private function loadFromExtensions(\DOMDocument $xml)
550 foreach ($xml->documentElement->childNodes as $node) {
551 if (!$node instanceof \DOMElement || $node->namespaceURI === self::NS) {
555 $values = static::convertDomElementToArray($node);
556 if (!is_array($values)) {
560 $this->container->loadFromExtension($node->namespaceURI, $values);
565 * Converts a \DomElement object to a PHP array.
567 * The following rules applies during the conversion:
569 * * Each tag is converted to a key value or an array
570 * if there is more than one "value"
572 * * The content of a tag is set under a "value" key (<foo>bar</foo>)
573 * if the tag also has some nested tags
575 * * The attributes are converted to keys (<foo foo="bar"/>)
577 * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
579 * @param \DomElement $element A \DomElement instance
581 * @return array A PHP array
583 public static function convertDomElementToArray(\DOMElement $element)
585 return XmlUtils::convertDomElementToArray($element);