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

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