vendor/symfony/dependency-injection/Loader/XmlFileLoader.php line 269

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\DependencyInjection\Loader;
  11. use Symfony\Component\Config\Util\XmlUtils;
  12. use Symfony\Component\DependencyInjection\Alias;
  13. use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
  14. use Symfony\Component\DependencyInjection\Argument\BoundArgument;
  15. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  16. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  17. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  18. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
  19. use Symfony\Component\DependencyInjection\ChildDefinition;
  20. use Symfony\Component\DependencyInjection\ContainerBuilder;
  21. use Symfony\Component\DependencyInjection\ContainerInterface;
  22. use Symfony\Component\DependencyInjection\Definition;
  23. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  24. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  25. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  26. use Symfony\Component\DependencyInjection\Reference;
  27. use Symfony\Component\ExpressionLanguage\Expression;
  28. /**
  29.  * XmlFileLoader loads XML files service definitions.
  30.  *
  31.  * @author Fabien Potencier <fabien@symfony.com>
  32.  */
  33. class XmlFileLoader extends FileLoader
  34. {
  35.     public const NS 'http://symfony.com/schema/dic/services';
  36.     protected $autoRegisterAliasesForSinglyImplementedInterfaces false;
  37.     /**
  38.      * {@inheritdoc}
  39.      */
  40.     public function load($resourcestring $type null)
  41.     {
  42.         $path $this->locator->locate($resource);
  43.         $xml $this->parseFileToDOM($path);
  44.         $this->container->fileExists($path);
  45.         $defaults $this->getServiceDefaults($xml$path);
  46.         // anonymous services
  47.         $this->processAnonymousServices($xml$path);
  48.         // imports
  49.         $this->parseImports($xml$path);
  50.         // parameters
  51.         $this->parseParameters($xml$path);
  52.         // extensions
  53.         $this->loadFromExtensions($xml);
  54.         // services
  55.         try {
  56.             $this->parseDefinitions($xml$path$defaults);
  57.         } finally {
  58.             $this->instanceof = [];
  59.             $this->registerAliasesForSinglyImplementedInterfaces();
  60.         }
  61.     }
  62.     /**
  63.      * {@inheritdoc}
  64.      */
  65.     public function supports($resourcestring $type null)
  66.     {
  67.         if (!\is_string($resource)) {
  68.             return false;
  69.         }
  70.         if (null === $type && 'xml' === pathinfo($resource\PATHINFO_EXTENSION)) {
  71.             return true;
  72.         }
  73.         return 'xml' === $type;
  74.     }
  75.     private function parseParameters(\DOMDocument $xmlstring $file)
  76.     {
  77.         if ($parameters $this->getChildren($xml->documentElement'parameters')) {
  78.             $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter'$file));
  79.         }
  80.     }
  81.     private function parseImports(\DOMDocument $xmlstring $file)
  82.     {
  83.         $xpath = new \DOMXPath($xml);
  84.         $xpath->registerNamespace('container'self::NS);
  85.         if (false === $imports $xpath->query('//container:imports/container:import')) {
  86.             return;
  87.         }
  88.         $defaultDirectory \dirname($file);
  89.         foreach ($imports as $import) {
  90.             $this->setCurrentDir($defaultDirectory);
  91.             $this->import($import->getAttribute('resource'), XmlUtils::phpize($import->getAttribute('type')) ?: nullXmlUtils::phpize($import->getAttribute('ignore-errors')) ?: false$file);
  92.         }
  93.     }
  94.     private function parseDefinitions(\DOMDocument $xmlstring $fileDefinition $defaults)
  95.     {
  96.         $xpath = new \DOMXPath($xml);
  97.         $xpath->registerNamespace('container'self::NS);
  98.         if (false === $services $xpath->query('//container:services/container:service|//container:services/container:prototype|//container:services/container:stack')) {
  99.             return;
  100.         }
  101.         $this->setCurrentDir(\dirname($file));
  102.         $this->instanceof = [];
  103.         $this->isLoadingInstanceof true;
  104.         $instanceof $xpath->query('//container:services/container:instanceof');
  105.         foreach ($instanceof as $service) {
  106.             $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service$file, new Definition()));
  107.         }
  108.         $this->isLoadingInstanceof false;
  109.         foreach ($services as $service) {
  110.             if ('stack' === $service->tagName) {
  111.                 $service->setAttribute('parent''-');
  112.                 $definition $this->parseDefinition($service$file$defaults)
  113.                     ->setTags(array_merge_recursive(['container.stack' => [[]]], $defaults->getTags()))
  114.                 ;
  115.                 $this->setDefinition($id = (string) $service->getAttribute('id'), $definition);
  116.                 $stack = [];
  117.                 foreach ($this->getChildren($service'service') as $k => $frame) {
  118.                     $k $frame->getAttribute('id') ?: $k;
  119.                     $frame->setAttribute('id'$id.'" at index "'.$k);
  120.                     if ($alias $frame->getAttribute('alias')) {
  121.                         $this->validateAlias($frame$file);
  122.                         $stack[$k] = new Reference($alias);
  123.                     } else {
  124.                         $stack[$k] = $this->parseDefinition($frame$file$defaults)
  125.                             ->setInstanceofConditionals($this->instanceof);
  126.                     }
  127.                 }
  128.                 $definition->setArguments($stack);
  129.             } elseif (null !== $definition $this->parseDefinition($service$file$defaults)) {
  130.                 if ('prototype' === $service->tagName) {
  131.                     $excludes array_column($this->getChildren($service'exclude'), 'nodeValue');
  132.                     if ($service->hasAttribute('exclude')) {
  133.                         if (\count($excludes) > 0) {
  134.                             throw new InvalidArgumentException('You cannot use both the attribute "exclude" and <exclude> tags at the same time.');
  135.                         }
  136.                         $excludes = [$service->getAttribute('exclude')];
  137.                     }
  138.                     $this->registerClasses($definition, (string) $service->getAttribute('namespace'), (string) $service->getAttribute('resource'), $excludes);
  139.                 } else {
  140.                     $this->setDefinition((string) $service->getAttribute('id'), $definition);
  141.                 }
  142.             }
  143.         }
  144.     }
  145.     private function getServiceDefaults(\DOMDocument $xmlstring $file): Definition
  146.     {
  147.         $xpath = new \DOMXPath($xml);
  148.         $xpath->registerNamespace('container'self::NS);
  149.         if (null === $defaultsNode $xpath->query('//container:services/container:defaults')->item(0)) {
  150.             return new Definition();
  151.         }
  152.         $defaultsNode->setAttribute('id''<defaults>');
  153.         return $this->parseDefinition($defaultsNode$file, new Definition());
  154.     }
  155.     /**
  156.      * Parses an individual Definition.
  157.      */
  158.     private function parseDefinition(\DOMElement $servicestring $fileDefinition $defaults): ?Definition
  159.     {
  160.         if ($alias $service->getAttribute('alias')) {
  161.             $this->validateAlias($service$file);
  162.             $this->container->setAlias((string) $service->getAttribute('id'), $alias = new Alias($alias));
  163.             if ($publicAttr $service->getAttribute('public')) {
  164.                 $alias->setPublic(XmlUtils::phpize($publicAttr));
  165.             } elseif ($defaults->getChanges()['public'] ?? false) {
  166.                 $alias->setPublic($defaults->isPublic());
  167.             }
  168.             if ($deprecated $this->getChildren($service'deprecated')) {
  169.                 $message $deprecated[0]->nodeValue ?: '';
  170.                 $package $deprecated[0]->getAttribute('package') ?: '';
  171.                 $version $deprecated[0]->getAttribute('version') ?: '';
  172.                 if (!$deprecated[0]->hasAttribute('package')) {
  173.                     trigger_deprecation('symfony/dependency-injection''5.1''Not setting the attribute "package" of the node "deprecated" in "%s" is deprecated.'$file);
  174.                 }
  175.                 if (!$deprecated[0]->hasAttribute('version')) {
  176.                     trigger_deprecation('symfony/dependency-injection''5.1''Not setting the attribute "version" of the node "deprecated" in "%s" is deprecated.'$file);
  177.                 }
  178.                 $alias->setDeprecated($package$version$message);
  179.             }
  180.             return null;
  181.         }
  182.         if ($this->isLoadingInstanceof) {
  183.             $definition = new ChildDefinition('');
  184.         } elseif ($parent $service->getAttribute('parent')) {
  185.             $definition = new ChildDefinition($parent);
  186.         } else {
  187.             $definition = new Definition();
  188.         }
  189.         if ($defaults->getChanges()['public'] ?? false) {
  190.             $definition->setPublic($defaults->isPublic());
  191.         }
  192.         $definition->setAutowired($defaults->isAutowired());
  193.         $definition->setAutoconfigured($defaults->isAutoconfigured());
  194.         $definition->setChanges([]);
  195.         foreach (['class''public''shared''synthetic''abstract'] as $key) {
  196.             if ($value $service->getAttribute($key)) {
  197.                 $method 'set'.$key;
  198.                 $definition->$method($value XmlUtils::phpize($value));
  199.             }
  200.         }
  201.         if ($value $service->getAttribute('lazy')) {
  202.             $definition->setLazy((bool) $value XmlUtils::phpize($value));
  203.             if (\is_string($value)) {
  204.                 $definition->addTag('proxy', ['interface' => $value]);
  205.             }
  206.         }
  207.         if ($value $service->getAttribute('autowire')) {
  208.             $definition->setAutowired(XmlUtils::phpize($value));
  209.         }
  210.         if ($value $service->getAttribute('autoconfigure')) {
  211.             $definition->setAutoconfigured(XmlUtils::phpize($value));
  212.         }
  213.         if ($files $this->getChildren($service'file')) {
  214.             $definition->setFile($files[0]->nodeValue);
  215.         }
  216.         if ($deprecated $this->getChildren($service'deprecated')) {
  217.             $message $deprecated[0]->nodeValue ?: '';
  218.             $package $deprecated[0]->getAttribute('package') ?: '';
  219.             $version $deprecated[0]->getAttribute('version') ?: '';
  220.             if ('' === $package) {
  221.                 trigger_deprecation('symfony/dependency-injection''5.1''Not setting the attribute "package" of the node "deprecated" in "%s" is deprecated.'$file);
  222.             }
  223.             if ('' === $version) {
  224.                 trigger_deprecation('symfony/dependency-injection''5.1''Not setting the attribute "version" of the node "deprecated" in "%s" is deprecated.'$file);
  225.             }
  226.             $definition->setDeprecated($package$version$message);
  227.         }
  228.         $definition->setArguments($this->getArgumentsAsPhp($service'argument'$file$definition instanceof ChildDefinition));
  229.         $definition->setProperties($this->getArgumentsAsPhp($service'property'$file));
  230.         if ($factories $this->getChildren($service'factory')) {
  231.             $factory $factories[0];
  232.             if ($function $factory->getAttribute('function')) {
  233.                 $definition->setFactory($function);
  234.             } else {
  235.                 if ($childService $factory->getAttribute('service')) {
  236.                     $class = new Reference($childServiceContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
  237.                 } else {
  238.                     $class $factory->hasAttribute('class') ? $factory->getAttribute('class') : null;
  239.                 }
  240.                 $definition->setFactory([$class$factory->getAttribute('method') ?: '__invoke']);
  241.             }
  242.         }
  243.         if ($configurators $this->getChildren($service'configurator')) {
  244.             $configurator $configurators[0];
  245.             if ($function $configurator->getAttribute('function')) {
  246.                 $definition->setConfigurator($function);
  247.             } else {
  248.                 if ($childService $configurator->getAttribute('service')) {
  249.                     $class = new Reference($childServiceContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
  250.                 } else {
  251.                     $class $configurator->getAttribute('class');
  252.                 }
  253.                 $definition->setConfigurator([$class$configurator->getAttribute('method') ?: '__invoke']);
  254.             }
  255.         }
  256.         foreach ($this->getChildren($service'call') as $call) {
  257.             $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call'argument'$file), XmlUtils::phpize($call->getAttribute('returns-clone')));
  258.         }
  259.         $tags $this->getChildren($service'tag');
  260.         foreach ($tags as $tag) {
  261.             $parameters = [];
  262.             $tagName $tag->nodeValue;
  263.             foreach ($tag->attributes as $name => $node) {
  264.                 if ('name' === $name && '' === $tagName) {
  265.                     continue;
  266.                 }
  267.                 if (false !== strpos($name'-') && false === strpos($name'_') && !\array_key_exists($normalizedName str_replace('-''_'$name), $parameters)) {
  268.                     $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
  269.                 }
  270.                 // keep not normalized key
  271.                 $parameters[$name] = XmlUtils::phpize($node->nodeValue);
  272.             }
  273.             if ('' === $tagName && '' === $tagName $tag->getAttribute('name')) {
  274.                 throw new InvalidArgumentException(sprintf('The tag name for service "%s" in "%s" must be a non-empty string.', (string) $service->getAttribute('id'), $file));
  275.             }
  276.             $definition->addTag($tagName$parameters);
  277.         }
  278.         $definition->setTags(array_merge_recursive($definition->getTags(), $defaults->getTags()));
  279.         $bindings $this->getArgumentsAsPhp($service'bind'$file);
  280.         $bindingType $this->isLoadingInstanceof BoundArgument::INSTANCEOF_BINDING BoundArgument::SERVICE_BINDING;
  281.         foreach ($bindings as $argument => $value) {
  282.             $bindings[$argument] = new BoundArgument($valuetrue$bindingType$file);
  283.         }
  284.         // deep clone, to avoid multiple process of the same instance in the passes
  285.         $bindings array_merge(unserialize(serialize($defaults->getBindings())), $bindings);
  286.         if ($bindings) {
  287.             $definition->setBindings($bindings);
  288.         }
  289.         if ($decorates $service->getAttribute('decorates')) {
  290.             $decorationOnInvalid $service->getAttribute('decoration-on-invalid') ?: 'exception';
  291.             if ('exception' === $decorationOnInvalid) {
  292.                 $invalidBehavior ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  293.             } elseif ('ignore' === $decorationOnInvalid) {
  294.                 $invalidBehavior ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  295.             } elseif ('null' === $decorationOnInvalid) {
  296.                 $invalidBehavior ContainerInterface::NULL_ON_INVALID_REFERENCE;
  297.             } else {
  298.                 throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration-on-invalid" on service "%s". Did you mean "exception", "ignore" or "null" in "%s"?'$decorationOnInvalid, (string) $service->getAttribute('id'), $file));
  299.             }
  300.             $renameId $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
  301.             $priority $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
  302.             $definition->setDecoratedService($decorates$renameId$priority$invalidBehavior);
  303.         }
  304.         return $definition;
  305.     }
  306.     /**
  307.      * Parses an XML file to a \DOMDocument.
  308.      *
  309.      * @throws InvalidArgumentException When loading of XML file returns error
  310.      */
  311.     private function parseFileToDOM(string $file): \DOMDocument
  312.     {
  313.         try {
  314.             $dom XmlUtils::loadFile($file, [$this'validateSchema']);
  315.         } catch (\InvalidArgumentException $e) {
  316.             throw new InvalidArgumentException(sprintf('Unable to parse file "%s": '$file).$e->getMessage(), $e->getCode(), $e);
  317.         }
  318.         $this->validateExtensions($dom$file);
  319.         return $dom;
  320.     }
  321.     /**
  322.      * Processes anonymous services.
  323.      */
  324.     private function processAnonymousServices(\DOMDocument $xmlstring $file)
  325.     {
  326.         $definitions = [];
  327.         $count 0;
  328.         $suffix '~'.ContainerBuilder::hash($file);
  329.         $xpath = new \DOMXPath($xml);
  330.         $xpath->registerNamespace('container'self::NS);
  331.         // anonymous services as arguments/properties
  332.         if (false !== $nodes $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]|//container:bind[not(@id)]|//container:factory[not(@service)]|//container:configurator[not(@service)]')) {
  333.             foreach ($nodes as $node) {
  334.                 if ($services $this->getChildren($node'service')) {
  335.                     // give it a unique name
  336.                     $id sprintf('.%d_%s', ++$countpreg_replace('/^.*\\\\/'''$services[0]->getAttribute('class')).$suffix);
  337.                     $node->setAttribute('id'$id);
  338.                     $node->setAttribute('service'$id);
  339.                     $definitions[$id] = [$services[0], $file];
  340.                     $services[0]->setAttribute('id'$id);
  341.                     // anonymous services are always private
  342.                     // we could not use the constant false here, because of XML parsing
  343.                     $services[0]->setAttribute('public''false');
  344.                 }
  345.             }
  346.         }
  347.         // anonymous services "in the wild"
  348.         if (false !== $nodes $xpath->query('//container:services/container:service[not(@id)]')) {
  349.             foreach ($nodes as $node) {
  350.                 throw new InvalidArgumentException(sprintf('Top-level services must have "id" attribute, none found in "%s" at line %d.'$file$node->getLineNo()));
  351.             }
  352.         }
  353.         // resolve definitions
  354.         uksort($definitions'strnatcmp');
  355.         foreach (array_reverse($definitions) as $id => [$domElement$file]) {
  356.             if (null !== $definition $this->parseDefinition($domElement$file, new Definition())) {
  357.                 $this->setDefinition($id$definition);
  358.             }
  359.         }
  360.     }
  361.     private function getArgumentsAsPhp(\DOMElement $nodestring $namestring $filebool $isChildDefinition false): array
  362.     {
  363.         $arguments = [];
  364.         foreach ($this->getChildren($node$name) as $arg) {
  365.             if ($arg->hasAttribute('name')) {
  366.                 $arg->setAttribute('key'$arg->getAttribute('name'));
  367.             }
  368.             // this is used by ChildDefinition to overwrite a specific
  369.             // argument of the parent definition
  370.             if ($arg->hasAttribute('index')) {
  371.                 $key = ($isChildDefinition 'index_' '').$arg->getAttribute('index');
  372.             } elseif (!$arg->hasAttribute('key')) {
  373.                 // Append an empty argument, then fetch its key to overwrite it later
  374.                 $arguments[] = null;
  375.                 $keys array_keys($arguments);
  376.                 $key array_pop($keys);
  377.             } else {
  378.                 $key $arg->getAttribute('key');
  379.             }
  380.             $onInvalid $arg->getAttribute('on-invalid');
  381.             $invalidBehavior ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  382.             if ('ignore' == $onInvalid) {
  383.                 $invalidBehavior ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  384.             } elseif ('ignore_uninitialized' == $onInvalid) {
  385.                 $invalidBehavior ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
  386.             } elseif ('null' == $onInvalid) {
  387.                 $invalidBehavior ContainerInterface::NULL_ON_INVALID_REFERENCE;
  388.             }
  389.             switch ($arg->getAttribute('type')) {
  390.                 case 'service':
  391.                     if ('' === $arg->getAttribute('id')) {
  392.                         throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".'$name$file));
  393.                     }
  394.                     $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior);
  395.                     break;
  396.                 case 'expression':
  397.                     if (!class_exists(Expression::class)) {
  398.                         throw new \LogicException('The type="expression" attribute cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
  399.                     }
  400.                     $arguments[$key] = new Expression($arg->nodeValue);
  401.                     break;
  402.                 case 'collection':
  403.                     $arguments[$key] = $this->getArgumentsAsPhp($arg$name$file);
  404.                     break;
  405.                 case 'iterator':
  406.                     $arg $this->getArgumentsAsPhp($arg$name$file);
  407.                     try {
  408.                         $arguments[$key] = new IteratorArgument($arg);
  409.                     } catch (InvalidArgumentException $e) {
  410.                         throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="iterator" only accepts collections of type="service" references in "%s".'$name$file));
  411.                     }
  412.                     break;
  413.                 case 'service_closure':
  414.                     if ('' === $arg->getAttribute('id')) {
  415.                         throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service_closure" has no or empty "id" attribute in "%s".'$name$file));
  416.                     }
  417.                     $arguments[$key] = new ServiceClosureArgument(new Reference($arg->getAttribute('id'), $invalidBehavior));
  418.                     break;
  419.                 case 'service_locator':
  420.                     $arg $this->getArgumentsAsPhp($arg$name$file);
  421.                     try {
  422.                         $arguments[$key] = new ServiceLocatorArgument($arg);
  423.                     } catch (InvalidArgumentException $e) {
  424.                         throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service_locator" only accepts maps of type="service" references in "%s".'$name$file));
  425.                     }
  426.                     break;
  427.                 case 'tagged':
  428.                 case 'tagged_iterator':
  429.                 case 'tagged_locator':
  430.                     $type $arg->getAttribute('type');
  431.                     $forLocator 'tagged_locator' === $type;
  432.                     if (!$arg->getAttribute('tag')) {
  433.                         throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="%s" has no or empty "tag" attribute in "%s".'$name$type$file));
  434.                     }
  435.                     $arguments[$key] = new TaggedIteratorArgument($arg->getAttribute('tag'), $arg->getAttribute('index-by') ?: null$arg->getAttribute('default-index-method') ?: null$forLocator$arg->getAttribute('default-priority-method') ?: null);
  436.                     if ($forLocator) {
  437.                         $arguments[$key] = new ServiceLocatorArgument($arguments[$key]);
  438.                     }
  439.                     break;
  440.                 case 'binary':
  441.                     if (false === $value base64_decode($arg->nodeValue)) {
  442.                         throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="binary" is not a valid base64 encoded string.'$name));
  443.                     }
  444.                     $arguments[$key] = $value;
  445.                     break;
  446.                 case 'abstract':
  447.                     $arguments[$key] = new AbstractArgument($arg->nodeValue);
  448.                     break;
  449.                 case 'string':
  450.                     $arguments[$key] = $arg->nodeValue;
  451.                     break;
  452.                 case 'constant':
  453.                     $arguments[$key] = \constant(trim($arg->nodeValue));
  454.                     break;
  455.                 default:
  456.                     $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
  457.             }
  458.         }
  459.         return $arguments;
  460.     }
  461.     /**
  462.      * Get child elements by name.
  463.      *
  464.      * @return \DOMElement[]
  465.      */
  466.     private function getChildren(\DOMNode $nodestring $name): array
  467.     {
  468.         $children = [];
  469.         foreach ($node->childNodes as $child) {
  470.             if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) {
  471.                 $children[] = $child;
  472.             }
  473.         }
  474.         return $children;
  475.     }
  476.     /**
  477.      * Validates a documents XML schema.
  478.      *
  479.      * @return bool
  480.      *
  481.      * @throws RuntimeException When extension references a non-existent XSD file
  482.      */
  483.     public function validateSchema(\DOMDocument $dom)
  484.     {
  485.         $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\''/'__DIR__.'/schema/dic/services/services-1.0.xsd')];
  486.         if ($element $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance''schemaLocation')) {
  487.             $items preg_split('/\s+/'$element);
  488.             for ($i 0$nb \count($items); $i $nb$i += 2) {
  489.                 if (!$this->container->hasExtension($items[$i])) {
  490.                     continue;
  491.                 }
  492.                 if (($extension $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
  493.                     $ns $extension->getNamespace();
  494.                     $path str_replace([$nsstr_replace('http://''https://'$ns)], str_replace('\\''/'$extension->getXsdValidationBasePath()).'/'$items[$i 1]);
  495.                     if (!is_file($path)) {
  496.                         throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s".'get_debug_type($extension), $path));
  497.                     }
  498.                     $schemaLocations[$items[$i]] = $path;
  499.                 }
  500.             }
  501.         }
  502.         $tmpfiles = [];
  503.         $imports '';
  504.         foreach ($schemaLocations as $namespace => $location) {
  505.             $parts explode('/'$location);
  506.             $locationstart 'file:///';
  507.             if (=== stripos($location'phar://')) {
  508.                 $tmpfile tempnam(sys_get_temp_dir(), 'symfony');
  509.                 if ($tmpfile) {
  510.                     copy($location$tmpfile);
  511.                     $tmpfiles[] = $tmpfile;
  512.                     $parts explode('/'str_replace('\\''/'$tmpfile));
  513.                 } else {
  514.                     array_shift($parts);
  515.                     $locationstart 'phar:///';
  516.                 }
  517.             } elseif ('\\' === \DIRECTORY_SEPARATOR && === strpos($location'\\\\')) {
  518.                 $locationstart '';
  519.             }
  520.             $drive '\\' === \DIRECTORY_SEPARATOR array_shift($parts).'/' '';
  521.             $location $locationstart.$drive.implode('/'array_map('rawurlencode'$parts));
  522.             $imports .= sprintf('  <xsd:import namespace="%s" schemaLocation="%s" />'."\n"$namespace$location);
  523.         }
  524.         $source = <<<EOF
  525. <?xml version="1.0" encoding="utf-8" ?>
  526. <xsd:schema xmlns="http://symfony.com/schema"
  527.     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  528.     targetNamespace="http://symfony.com/schema"
  529.     elementFormDefault="qualified">
  530.     <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
  531. $imports
  532. </xsd:schema>
  533. EOF
  534.         ;
  535.         if ($this->shouldEnableEntityLoader()) {
  536.             $disableEntities libxml_disable_entity_loader(false);
  537.             $valid = @$dom->schemaValidateSource($source);
  538.             libxml_disable_entity_loader($disableEntities);
  539.         } else {
  540.             $valid = @$dom->schemaValidateSource($source);
  541.         }
  542.         foreach ($tmpfiles as $tmpfile) {
  543.             @unlink($tmpfile);
  544.         }
  545.         return $valid;
  546.     }
  547.     private function shouldEnableEntityLoader(): bool
  548.     {
  549.         // Version prior to 8.0 can be enabled without deprecation
  550.         if (\PHP_VERSION_ID 80000) {
  551.             return true;
  552.         }
  553.         static $dom$schema;
  554.         if (null === $dom) {
  555.             $dom = new \DOMDocument();
  556.             $dom->loadXML('<?xml version="1.0"?><test/>');
  557.             $tmpfile tempnam(sys_get_temp_dir(), 'symfony');
  558.             register_shutdown_function(static function () use ($tmpfile) {
  559.                 @unlink($tmpfile);
  560.             });
  561.             $schema '<?xml version="1.0" encoding="utf-8"?>
  562. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  563.   <xsd:include schemaLocation="file:///'.str_replace('\\''/'$tmpfile).'" />
  564. </xsd:schema>';
  565.             file_put_contents($tmpfile'<?xml version="1.0" encoding="utf-8"?>
  566. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  567.   <xsd:element name="test" type="testType" />
  568.   <xsd:complexType name="testType"/>
  569. </xsd:schema>');
  570.         }
  571.         return !@$dom->schemaValidateSource($schema);
  572.     }
  573.     private function validateAlias(\DOMElement $aliasstring $file)
  574.     {
  575.         foreach ($alias->attributes as $name => $node) {
  576.             if (!\in_array($name, ['alias''id''public'])) {
  577.                 throw new InvalidArgumentException(sprintf('Invalid attribute "%s" defined for alias "%s" in "%s".'$name$alias->getAttribute('id'), $file));
  578.             }
  579.         }
  580.         foreach ($alias->childNodes as $child) {
  581.             if (!$child instanceof \DOMElement || self::NS !== $child->namespaceURI) {
  582.                 continue;
  583.             }
  584.             if (!\in_array($child->localName, ['deprecated'], true)) {
  585.                 throw new InvalidArgumentException(sprintf('Invalid child element "%s" defined for alias "%s" in "%s".'$child->localName$alias->getAttribute('id'), $file));
  586.             }
  587.         }
  588.     }
  589.     /**
  590.      * Validates an extension.
  591.      *
  592.      * @throws InvalidArgumentException When no extension is found corresponding to a tag
  593.      */
  594.     private function validateExtensions(\DOMDocument $domstring $file)
  595.     {
  596.         foreach ($dom->documentElement->childNodes as $node) {
  597.             if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
  598.                 continue;
  599.             }
  600.             // can it be handled by an extension?
  601.             if (!$this->container->hasExtension($node->namespaceURI)) {
  602.                 $extensionNamespaces array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
  603.                 throw new InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in "%s"). Looked for namespace "%s", found "%s".'$node->tagName$file$node->namespaceURI$extensionNamespaces implode('", "'$extensionNamespaces) : 'none'));
  604.             }
  605.         }
  606.     }
  607.     /**
  608.      * Loads from an extension.
  609.      */
  610.     private function loadFromExtensions(\DOMDocument $xml)
  611.     {
  612.         foreach ($xml->documentElement->childNodes as $node) {
  613.             if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) {
  614.                 continue;
  615.             }
  616.             $values = static::convertDomElementToArray($node);
  617.             if (!\is_array($values)) {
  618.                 $values = [];
  619.             }
  620.             $this->container->loadFromExtension($node->namespaceURI$values);
  621.         }
  622.     }
  623.     /**
  624.      * Converts a \DOMElement object to a PHP array.
  625.      *
  626.      * The following rules applies during the conversion:
  627.      *
  628.      *  * Each tag is converted to a key value or an array
  629.      *    if there is more than one "value"
  630.      *
  631.      *  * The content of a tag is set under a "value" key (<foo>bar</foo>)
  632.      *    if the tag also has some nested tags
  633.      *
  634.      *  * The attributes are converted to keys (<foo foo="bar"/>)
  635.      *
  636.      *  * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
  637.      *
  638.      * @param \DOMElement $element A \DOMElement instance
  639.      *
  640.      * @return mixed
  641.      */
  642.     public static function convertDomElementToArray(\DOMElement $element)
  643.     {
  644.         return XmlUtils::convertDomElementToArray($element);
  645.     }
  646. }