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')) {
137 if ($publicAttr = $service->getAttribute('public')) {
138 $public = XmlUtils::phpize($publicAttr);
140 $this->container->setAlias((string) $service->getAttribute('id'), new Alias($alias, $public));
145 if ($parent = $service->getAttribute('parent')) {
146 $definition = new DefinitionDecorator($parent);
148 $definition = new Definition();
151 foreach (array('class', 'shared', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'lazy', 'abstract') as $key) {
152 if ($value = $service->getAttribute($key)) {
153 if (in_array($key, array('factory-class', 'factory-method', 'factory-service'))) {
154 @trigger_error(sprintf('The "%s" attribute of service "%s" in file "%s" is deprecated since version 2.6 and will be removed in 3.0. Use the "factory" element instead.', $key, (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
156 $method = 'set'.str_replace('-', '', $key);
157 $definition->$method(XmlUtils::phpize($value));
161 if ($value = $service->getAttribute('autowire')) {
162 $definition->setAutowired(XmlUtils::phpize($value));
165 if ($value = $service->getAttribute('scope')) {
166 $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
168 if ($triggerDeprecation) {
169 @trigger_error(sprintf('The "scope" attribute of service "%s" in file "%s" is deprecated since version 2.8 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
172 $definition->setScope(XmlUtils::phpize($value), false);
175 if ($value = $service->getAttribute('synchronized')) {
176 $triggerDeprecation = 'request' !== (string) $service->getAttribute('id');
178 if ($triggerDeprecation) {
179 @trigger_error(sprintf('The "synchronized" attribute of service "%s" in file "%s" is deprecated since version 2.7 and will be removed in 3.0.', (string) $service->getAttribute('id'), $file), E_USER_DEPRECATED);
182 $definition->setSynchronized(XmlUtils::phpize($value), $triggerDeprecation);
185 if ($files = $this->getChildren($service, 'file')) {
186 $definition->setFile($files[0]->nodeValue);
189 if ($deprecated = $this->getChildren($service, 'deprecated')) {
190 $definition->setDeprecated(true, $deprecated[0]->nodeValue ?: null);
193 $definition->setArguments($this->getArgumentsAsPhp($service, 'argument'));
194 $definition->setProperties($this->getArgumentsAsPhp($service, 'property'));
196 if ($factories = $this->getChildren($service, 'factory')) {
197 $factory = $factories[0];
198 if ($function = $factory->getAttribute('function')) {
199 $definition->setFactory($function);
201 $factoryService = $this->getChildren($factory, 'service');
203 if (isset($factoryService[0])) {
204 $class = $this->parseDefinition($factoryService[0], $file);
205 } elseif ($childService = $factory->getAttribute('service')) {
206 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
208 $class = $factory->getAttribute('class');
211 $definition->setFactory(array($class, $factory->getAttribute('method')));
215 if ($configurators = $this->getChildren($service, 'configurator')) {
216 $configurator = $configurators[0];
217 if ($function = $configurator->getAttribute('function')) {
218 $definition->setConfigurator($function);
220 $configuratorService = $this->getChildren($configurator, 'service');
222 if (isset($configuratorService[0])) {
223 $class = $this->parseDefinition($configuratorService[0], $file);
224 } elseif ($childService = $configurator->getAttribute('service')) {
225 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
227 $class = $configurator->getAttribute('class');
230 $definition->setConfigurator(array($class, $configurator->getAttribute('method')));
234 foreach ($this->getChildren($service, 'call') as $call) {
235 $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument'));
238 foreach ($this->getChildren($service, 'tag') as $tag) {
239 $parameters = array();
240 foreach ($tag->attributes as $name => $node) {
241 if ('name' === $name) {
245 if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
246 $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
248 // keep not normalized key for BC too
249 $parameters[$name] = XmlUtils::phpize($node->nodeValue);
252 if ('' === $tag->getAttribute('name')) {
253 throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $service->getAttribute('id'), $file));
256 $definition->addTag($tag->getAttribute('name'), $parameters);
259 foreach ($this->getChildren($service, 'autowiring-type') as $type) {
260 $definition->addAutowiringType($type->textContent);
263 if ($value = $service->getAttribute('decorates')) {
264 $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
265 $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
266 $definition->setDecoratedService($value, $renameId, $priority);
273 * Parses a XML file to a \DOMDocument.
275 * @param string $file Path to a file
277 * @return \DOMDocument
279 * @throws InvalidArgumentException When loading of XML file returns error
281 private function parseFileToDOM($file)
284 $dom = XmlUtils::loadFile($file, array($this, 'validateSchema'));
285 } catch (\InvalidArgumentException $e) {
286 throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e);
289 $this->validateExtensions($dom, $file);
295 * Processes anonymous services.
297 * @param \DOMDocument $xml
298 * @param string $file
300 private function processAnonymousServices(\DOMDocument $xml, $file)
302 $definitions = array();
305 $xpath = new \DOMXPath($xml);
306 $xpath->registerNamespace('container', self::NS);
308 // anonymous services as arguments/properties
309 if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) {
310 foreach ($nodes as $node) {
311 // give it a unique name
312 $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
313 $node->setAttribute('id', $id);
315 if ($services = $this->getChildren($node, 'service')) {
316 $definitions[$id] = array($services[0], $file, false);
317 $services[0]->setAttribute('id', $id);
319 // anonymous services are always private
320 // we could not use the constant false here, because of XML parsing
321 $services[0]->setAttribute('public', 'false');
326 // anonymous services "in the wild"
327 if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) {
328 foreach ($nodes as $node) {
329 // give it a unique name
330 $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
331 $node->setAttribute('id', $id);
332 $definitions[$id] = array($node, $file, true);
336 // resolve definitions
337 krsort($definitions);
338 foreach ($definitions as $id => $def) {
339 list($domElement, $file, $wild) = $def;
341 if (null !== $definition = $this->parseDefinition($domElement, $file)) {
342 $this->container->setDefinition($id, $definition);
345 if (true === $wild) {
346 $tmpDomElement = new \DOMElement('_services', null, self::NS);
347 $domElement->parentNode->replaceChild($tmpDomElement, $domElement);
348 $tmpDomElement->setAttribute('id', $id);
350 $domElement->parentNode->removeChild($domElement);
356 * Returns arguments as valid php types.
358 * @param \DOMElement $node
359 * @param string $name
360 * @param bool $lowercase
364 private function getArgumentsAsPhp(\DOMElement $node, $name, $lowercase = true)
366 $arguments = array();
367 foreach ($this->getChildren($node, $name) as $arg) {
368 if ($arg->hasAttribute('name')) {
369 $arg->setAttribute('key', $arg->getAttribute('name'));
372 // this is used by DefinitionDecorator to overwrite a specific
373 // argument of the parent definition
374 if ($arg->hasAttribute('index')) {
375 $key = 'index_'.$arg->getAttribute('index');
376 } elseif (!$arg->hasAttribute('key')) {
377 // Append an empty argument, then fetch its key to overwrite it later
379 $keys = array_keys($arguments);
380 $key = array_pop($keys);
382 $key = $arg->getAttribute('key');
384 // parameter keys are case insensitive
385 if ('parameter' == $name && $lowercase) {
386 $key = strtolower($key);
390 switch ($arg->getAttribute('type')) {
392 $onInvalid = $arg->getAttribute('on-invalid');
393 $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
394 if ('ignore' == $onInvalid) {
395 $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
396 } elseif ('null' == $onInvalid) {
397 $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
400 if ($strict = $arg->getAttribute('strict')) {
401 $strict = XmlUtils::phpize($strict);
406 $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior, $strict);
409 $arguments[$key] = new Expression($arg->nodeValue);
412 $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, false);
415 $arguments[$key] = $arg->nodeValue;
418 $arguments[$key] = constant(trim($arg->nodeValue));
421 $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
429 * Get child elements by name.
431 * @param \DOMNode $node
436 private function getChildren(\DOMNode $node, $name)
439 foreach ($node->childNodes as $child) {
440 if ($child instanceof \DOMElement && $child->localName === $name && $child->namespaceURI === self::NS) {
441 $children[] = $child;
449 * Validates a documents XML schema.
451 * @param \DOMDocument $dom
455 * @throws RuntimeException When extension references a non-existent XSD file
457 public function validateSchema(\DOMDocument $dom)
459 $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd'));
461 if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
462 $items = preg_split('/\s+/', $element);
463 for ($i = 0, $nb = count($items); $i < $nb; $i += 2) {
464 if (!$this->container->hasExtension($items[$i])) {
468 if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
469 $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
471 if (!is_file($path)) {
472 throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path));
475 $schemaLocations[$items[$i]] = $path;
482 foreach ($schemaLocations as $namespace => $location) {
483 $parts = explode('/', $location);
484 if (0 === stripos($location, 'phar://')) {
485 $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
487 copy($location, $tmpfile);
488 $tmpfiles[] = $tmpfile;
489 $parts = explode('/', str_replace('\\', '/', $tmpfile));
492 $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
493 $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
495 $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
499 <?xml version="1.0" encoding="utf-8" ?>
500 <xsd:schema xmlns="http://symfony.com/schema"
501 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
502 targetNamespace="http://symfony.com/schema"
503 elementFormDefault="qualified">
505 <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
511 $disableEntities = libxml_disable_entity_loader(false);
512 $valid = @$dom->schemaValidateSource($source);
513 libxml_disable_entity_loader($disableEntities);
515 foreach ($tmpfiles as $tmpfile) {
523 * Validates an extension.
525 * @param \DOMDocument $dom
526 * @param string $file
528 * @throws InvalidArgumentException When no extension is found corresponding to a tag
530 private function validateExtensions(\DOMDocument $dom, $file)
532 foreach ($dom->documentElement->childNodes as $node) {
533 if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
537 // can it be handled by an extension?
538 if (!$this->container->hasExtension($node->namespaceURI)) {
539 $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
540 throw new InvalidArgumentException(sprintf(
541 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
545 $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
552 * Loads from an extension.
554 * @param \DOMDocument $xml
556 private function loadFromExtensions(\DOMDocument $xml)
558 foreach ($xml->documentElement->childNodes as $node) {
559 if (!$node instanceof \DOMElement || $node->namespaceURI === self::NS) {
563 $values = static::convertDomElementToArray($node);
564 if (!is_array($values)) {
568 $this->container->loadFromExtension($node->namespaceURI, $values);
573 * Converts a \DomElement object to a PHP array.
575 * The following rules applies during the conversion:
577 * * Each tag is converted to a key value or an array
578 * if there is more than one "value"
580 * * The content of a tag is set under a "value" key (<foo>bar</foo>)
581 * if the tag also has some nested tags
583 * * The attributes are converted to keys (<foo foo="bar"/>)
585 * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
587 * @param \DomElement $element A \DomElement instance
589 * @return array A PHP array
591 public static function convertDomElementToArray(\DOMElement $element)
593 return XmlUtils::convertDomElementToArray($element);