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

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