vendor/symfony/dependency-injection/Dumper/PhpDumper.php line 1473

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\Dumper;
  11. use Composer\Autoload\ClassLoader;
  12. use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
  13. use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
  14. use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
  15. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  16. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  17. use Symfony\Component\DependencyInjection\Argument\ServiceLocator;
  18. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  19. use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
  20. use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass;
  21. use Symfony\Component\DependencyInjection\Compiler\ServiceReferenceGraphNode;
  22. use Symfony\Component\DependencyInjection\Container;
  23. use Symfony\Component\DependencyInjection\ContainerBuilder;
  24. use Symfony\Component\DependencyInjection\ContainerInterface;
  25. use Symfony\Component\DependencyInjection\Definition;
  26. use Symfony\Component\DependencyInjection\Exception\EnvParameterException;
  27. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  28. use Symfony\Component\DependencyInjection\Exception\LogicException;
  29. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  30. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  31. use Symfony\Component\DependencyInjection\ExpressionLanguage;
  32. use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;
  33. use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;
  34. use Symfony\Component\DependencyInjection\Loader\FileLoader;
  35. use Symfony\Component\DependencyInjection\Parameter;
  36. use Symfony\Component\DependencyInjection\Reference;
  37. use Symfony\Component\DependencyInjection\ServiceLocator as BaseServiceLocator;
  38. use Symfony\Component\DependencyInjection\TypedReference;
  39. use Symfony\Component\DependencyInjection\Variable;
  40. use Symfony\Component\ErrorHandler\DebugClassLoader;
  41. use Symfony\Component\ExpressionLanguage\Expression;
  42. use Symfony\Component\HttpKernel\Kernel;
  43. /**
  44.  * PhpDumper dumps a service container as a PHP class.
  45.  *
  46.  * @author Fabien Potencier <fabien@symfony.com>
  47.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  48.  */
  49. class PhpDumper extends Dumper
  50. {
  51.     /**
  52.      * Characters that might appear in the generated variable name as first character.
  53.      */
  54.     public const FIRST_CHARS 'abcdefghijklmnopqrstuvwxyz';
  55.     /**
  56.      * Characters that might appear in the generated variable name as any but the first character.
  57.      */
  58.     public const NON_FIRST_CHARS 'abcdefghijklmnopqrstuvwxyz0123456789_';
  59.     /**
  60.      * @var \SplObjectStorage<Definition, Variable>|null
  61.      */
  62.     private $definitionVariables;
  63.     private $referenceVariables;
  64.     private $variableCount;
  65.     private $inlinedDefinitions;
  66.     private $serviceCalls;
  67.     private $reservedVariables = ['instance''class''this''container'];
  68.     private $expressionLanguage;
  69.     private $targetDirRegex;
  70.     private $targetDirMaxMatches;
  71.     private $docStar;
  72.     private $serviceIdToMethodNameMap;
  73.     private $usedMethodNames;
  74.     private $namespace;
  75.     private $asFiles;
  76.     private $hotPathTag;
  77.     private $preloadTags;
  78.     private $inlineFactories;
  79.     private $inlineRequires;
  80.     private $inlinedRequires = [];
  81.     private $circularReferences = [];
  82.     private $singleUsePrivateIds = [];
  83.     private $preload = [];
  84.     private $addThrow false;
  85.     private $addGetService false;
  86.     private $locatedIds = [];
  87.     private $serviceLocatorTag;
  88.     private $exportedVariables = [];
  89.     private $baseClass;
  90.     /**
  91.      * @var ProxyDumper
  92.      */
  93.     private $proxyDumper;
  94.     /**
  95.      * {@inheritdoc}
  96.      */
  97.     public function __construct(ContainerBuilder $container)
  98.     {
  99.         if (!$container->isCompiled()) {
  100.             throw new LogicException('Cannot dump an uncompiled container.');
  101.         }
  102.         parent::__construct($container);
  103.     }
  104.     /**
  105.      * Sets the dumper to be used when dumping proxies in the generated container.
  106.      */
  107.     public function setProxyDumper(ProxyDumper $proxyDumper)
  108.     {
  109.         $this->proxyDumper $proxyDumper;
  110.     }
  111.     /**
  112.      * Dumps the service container as a PHP class.
  113.      *
  114.      * Available options:
  115.      *
  116.      *  * class:      The class name
  117.      *  * base_class: The base class name
  118.      *  * namespace:  The class namespace
  119.      *  * as_files:   To split the container in several files
  120.      *
  121.      * @return string|array A PHP class representing the service container or an array of PHP files if the "as_files" option is set
  122.      *
  123.      * @throws EnvParameterException When an env var exists but has not been dumped
  124.      */
  125.     public function dump(array $options = [])
  126.     {
  127.         $this->locatedIds = [];
  128.         $this->targetDirRegex null;
  129.         $this->inlinedRequires = [];
  130.         $this->exportedVariables = [];
  131.         $options array_merge([
  132.             'class' => 'ProjectServiceContainer',
  133.             'base_class' => 'Container',
  134.             'namespace' => '',
  135.             'as_files' => false,
  136.             'debug' => true,
  137.             'hot_path_tag' => 'container.hot_path',
  138.             'preload_tags' => ['container.preload''container.no_preload'],
  139.             'inline_factories_parameter' => 'container.dumper.inline_factories',
  140.             'inline_class_loader_parameter' => 'container.dumper.inline_class_loader',
  141.             'preload_classes' => [],
  142.             'service_locator_tag' => 'container.service_locator',
  143.             'build_time' => time(),
  144.         ], $options);
  145.         $this->addThrow $this->addGetService false;
  146.         $this->namespace $options['namespace'];
  147.         $this->asFiles $options['as_files'];
  148.         $this->hotPathTag $options['hot_path_tag'];
  149.         $this->preloadTags $options['preload_tags'];
  150.         $this->inlineFactories $this->asFiles && $options['inline_factories_parameter'] && $this->container->hasParameter($options['inline_factories_parameter']) && $this->container->getParameter($options['inline_factories_parameter']);
  151.         $this->inlineRequires $options['inline_class_loader_parameter'] && ($this->container->hasParameter($options['inline_class_loader_parameter']) ? $this->container->getParameter($options['inline_class_loader_parameter']) : (\PHP_VERSION_ID 70400 || $options['debug']));
  152.         $this->serviceLocatorTag $options['service_locator_tag'];
  153.         if (!str_starts_with($baseClass $options['base_class'], '\\') && 'Container' !== $baseClass) {
  154.             $baseClass sprintf('%s\%s'$options['namespace'] ? '\\'.$options['namespace'] : ''$baseClass);
  155.             $this->baseClass $baseClass;
  156.         } elseif ('Container' === $baseClass) {
  157.             $this->baseClass Container::class;
  158.         } else {
  159.             $this->baseClass $baseClass;
  160.         }
  161.         $this->initializeMethodNamesMap('Container' === $baseClass Container::class : $baseClass);
  162.         if ($this->getProxyDumper() instanceof NullDumper) {
  163.             (new AnalyzeServiceReferencesPass(truefalse))->process($this->container);
  164.             try {
  165.                 (new CheckCircularReferencesPass())->process($this->container);
  166.             } catch (ServiceCircularReferenceException $e) {
  167.                 $path $e->getPath();
  168.                 end($path);
  169.                 $path[key($path)] .= '". Try running "composer require symfony/proxy-manager-bridge';
  170.                 throw new ServiceCircularReferenceException($e->getServiceId(), $path);
  171.             }
  172.         }
  173.         $this->analyzeReferences();
  174.         $this->docStar $options['debug'] ? '*' '';
  175.         if (!empty($options['file']) && is_dir($dir = \dirname($options['file']))) {
  176.             // Build a regexp where the first root dirs are mandatory,
  177.             // but every other sub-dir is optional up to the full path in $dir
  178.             // Mandate at least 1 root dir and not more than 5 optional dirs.
  179.             $dir explode(\DIRECTORY_SEPARATORrealpath($dir));
  180.             $i = \count($dir);
  181.             if (+ (int) ('\\' === \DIRECTORY_SEPARATOR) <= $i) {
  182.                 $regex '';
  183.                 $lastOptionalDir $i $i : (+ (int) ('\\' === \DIRECTORY_SEPARATOR));
  184.                 $this->targetDirMaxMatches $i $lastOptionalDir;
  185.                 while (--$i >= $lastOptionalDir) {
  186.                     $regex sprintf('(%s%s)?'preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex);
  187.                 }
  188.                 do {
  189.                     $regex preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#').$regex;
  190.                 } while (< --$i);
  191.                 $this->targetDirRegex '#(^|file://|[:;, \|\r\n])'.preg_quote($dir[0], '#').$regex.'#';
  192.             }
  193.         }
  194.         $proxyClasses $this->inlineFactories $this->generateProxyClasses() : null;
  195.         if ($options['preload_classes']) {
  196.             $this->preload array_combine($options['preload_classes'], $options['preload_classes']);
  197.         }
  198.         $code =
  199.             $this->startClass($options['class'], $baseClass$this->inlineFactories && $proxyClasses).
  200.             $this->addServices($services).
  201.             $this->addDeprecatedAliases().
  202.             $this->addDefaultParametersMethod()
  203.         ;
  204.         $proxyClasses $proxyClasses ?? $this->generateProxyClasses();
  205.         if ($this->addGetService) {
  206.             $code preg_replace(
  207.                 "/(\r?\n\r?\n    public function __construct.+?\\{\r?\n)/s",
  208.                 "\n    protected \$getService;$1        \$this->getService = \\Closure::fromCallable([\$this, 'getService']);\n",
  209.                 $code,
  210.                 1
  211.             );
  212.         }
  213.         if ($this->asFiles) {
  214.             $fileTemplate = <<<EOF
  215. <?php
  216. use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
  217. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  218. /*{$this->docStar}
  219.  * @internal This class has been auto-generated by the Symfony Dependency Injection Component.
  220.  */
  221. class %s extends {$options['class']}
  222. {%s}
  223. EOF;
  224.             $files = [];
  225.             $preloadedFiles = [];
  226.             $ids $this->container->getRemovedIds();
  227.             foreach ($this->container->getDefinitions() as $id => $definition) {
  228.                 if (!$definition->isPublic()) {
  229.                     $ids[$id] = true;
  230.                 }
  231.             }
  232.             if ($ids array_keys($ids)) {
  233.                 sort($ids);
  234.                 $c "<?php\n\nreturn [\n";
  235.                 foreach ($ids as $id) {
  236.                     $c .= '    '.$this->doExport($id)." => true,\n";
  237.                 }
  238.                 $files['removed-ids.php'] = $c."];\n";
  239.             }
  240.             if (!$this->inlineFactories) {
  241.                 foreach ($this->generateServiceFiles($services) as $file => [$c$preload]) {
  242.                     $files[$file] = sprintf($fileTemplatesubstr($file0, -4), $c);
  243.                     if ($preload) {
  244.                         $preloadedFiles[$file] = $file;
  245.                     }
  246.                 }
  247.                 foreach ($proxyClasses as $file => $c) {
  248.                     $files[$file] = "<?php\n".$c;
  249.                     $preloadedFiles[$file] = $file;
  250.                 }
  251.             }
  252.             $code .= $this->endClass();
  253.             if ($this->inlineFactories && $proxyClasses) {
  254.                 $files['proxy-classes.php'] = "<?php\n\n";
  255.                 foreach ($proxyClasses as $c) {
  256.                     $files['proxy-classes.php'] .= $c;
  257.                 }
  258.             }
  259.             $files[$options['class'].'.php'] = $code;
  260.             $hash ucfirst(strtr(ContainerBuilder::hash($files), '._''xx'));
  261.             $code = [];
  262.             foreach ($files as $file => $c) {
  263.                 $code["Container{$hash}/{$file}"] = substr_replace($c"<?php\n\nnamespace Container{$hash};\n"06);
  264.                 if (isset($preloadedFiles[$file])) {
  265.                     $preloadedFiles[$file] = "Container{$hash}/{$file}";
  266.                 }
  267.             }
  268.             $namespaceLine $this->namespace "\nnamespace {$this->namespace};\n" '';
  269.             $time $options['build_time'];
  270.             $id hash('crc32'$hash.$time);
  271.             $this->asFiles false;
  272.             if ($this->preload && null !== $autoloadFile $this->getAutoloadFile()) {
  273.                 $autoloadFile trim($this->export($autoloadFile), '()\\');
  274.                 $preloadedFiles array_reverse($preloadedFiles);
  275.                 if ('' !== $preloadedFiles implode("';\nrequire __DIR__.'/"$preloadedFiles)) {
  276.                     $preloadedFiles "require __DIR__.'/$preloadedFiles';\n";
  277.                 }
  278.                 $code[$options['class'].'.preload.php'] = <<<EOF
  279. <?php
  280. // This file has been auto-generated by the Symfony Dependency Injection Component
  281. // You can reference it in the "opcache.preload" php.ini setting on PHP >= 7.4 when preloading is desired
  282. use Symfony\Component\DependencyInjection\Dumper\Preloader;
  283. if (in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {
  284.     return;
  285. }
  286. require $autoloadFile;
  287. (require __DIR__.'/{$options['class']}.php')->set(\\Container{$hash}\\{$options['class']}::class, null);
  288. $preloadedFiles
  289. \$classes = [];
  290. EOF;
  291.                 foreach ($this->preload as $class) {
  292.                     if (!$class || str_contains($class'$') || \in_array($class, ['int''float''string''bool''resource''object''array''null''callable''iterable''mixed''void'], true)) {
  293.                         continue;
  294.                     }
  295.                     if (!(class_exists($classfalse) || interface_exists($classfalse) || trait_exists($classfalse)) || ((new \ReflectionClass($class))->isUserDefined() && !\in_array($class, ['Attribute''JsonException''ReturnTypeWillChange''Stringable''UnhandledMatchError''ValueError'], true))) {
  296.                         $code[$options['class'].'.preload.php'] .= sprintf("\$classes[] = '%s';\n"$class);
  297.                     }
  298.                 }
  299.                 $code[$options['class'].'.preload.php'] .= <<<'EOF'
  300. $preloaded = Preloader::preload($classes);
  301. EOF;
  302.             }
  303.             $code[$options['class'].'.php'] = <<<EOF
  304. <?php
  305. {$namespaceLine}
  306. // This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
  307. if (\\class_exists(\\Container{$hash}\\{$options['class']}::class, false)) {
  308.     // no-op
  309. } elseif (!include __DIR__.'/Container{$hash}/{$options['class']}.php') {
  310.     touch(__DIR__.'/Container{$hash}.legacy');
  311.     return;
  312. }
  313. if (!\\class_exists({$options['class']}::class, false)) {
  314.     \\class_alias(\\Container{$hash}\\{$options['class']}::class, {$options['class']}::class, false);
  315. }
  316. return new \\Container{$hash}\\{$options['class']}([
  317.     'container.build_hash' => '$hash',
  318.     'container.build_id' => '$id',
  319.     'container.build_time' => $time,
  320. ], __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}');
  321. EOF;
  322.         } else {
  323.             $code .= $this->endClass();
  324.             foreach ($proxyClasses as $c) {
  325.                 $code .= $c;
  326.             }
  327.         }
  328.         $this->targetDirRegex null;
  329.         $this->inlinedRequires = [];
  330.         $this->circularReferences = [];
  331.         $this->locatedIds = [];
  332.         $this->exportedVariables = [];
  333.         $this->preload = [];
  334.         $unusedEnvs = [];
  335.         foreach ($this->container->getEnvCounters() as $env => $use) {
  336.             if (!$use) {
  337.                 $unusedEnvs[] = $env;
  338.             }
  339.         }
  340.         if ($unusedEnvs) {
  341.             throw new EnvParameterException($unusedEnvsnull'Environment variables "%s" are never used. Please, check your container\'s configuration.');
  342.         }
  343.         return $code;
  344.     }
  345.     /**
  346.      * Retrieves the currently set proxy dumper or instantiates one.
  347.      */
  348.     private function getProxyDumper(): ProxyDumper
  349.     {
  350.         if (!$this->proxyDumper) {
  351.             $this->proxyDumper = new NullDumper();
  352.         }
  353.         return $this->proxyDumper;
  354.     }
  355.     private function analyzeReferences()
  356.     {
  357.         (new AnalyzeServiceReferencesPass(false, !$this->getProxyDumper() instanceof NullDumper))->process($this->container);
  358.         $checkedNodes = [];
  359.         $this->circularReferences = [];
  360.         $this->singleUsePrivateIds = [];
  361.         foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) {
  362.             if (!$node->getValue() instanceof Definition) {
  363.                 continue;
  364.             }
  365.             if ($this->isSingleUsePrivateNode($node)) {
  366.                 $this->singleUsePrivateIds[$id] = $id;
  367.             }
  368.             $this->collectCircularReferences($id$node->getOutEdges(), $checkedNodes);
  369.         }
  370.         $this->container->getCompiler()->getServiceReferenceGraph()->clear();
  371.         $this->singleUsePrivateIds array_diff_key($this->singleUsePrivateIds$this->circularReferences);
  372.     }
  373.     private function collectCircularReferences(string $sourceId, array $edges, array &$checkedNodes, array &$loops = [], array $path = [], bool $byConstructor true): void
  374.     {
  375.         $path[$sourceId] = $byConstructor;
  376.         $checkedNodes[$sourceId] = true;
  377.         foreach ($edges as $edge) {
  378.             $node $edge->getDestNode();
  379.             $id $node->getId();
  380.             if ($sourceId === $id || !$node->getValue() instanceof Definition || $edge->isLazy() || $edge->isWeak()) {
  381.                 continue;
  382.             }
  383.             if (isset($path[$id])) {
  384.                 $loop null;
  385.                 $loopByConstructor $edge->isReferencedByConstructor();
  386.                 $pathInLoop = [$id, []];
  387.                 foreach ($path as $k => $pathByConstructor) {
  388.                     if (null !== $loop) {
  389.                         $loop[] = $k;
  390.                         $pathInLoop[1][$k] = $pathByConstructor;
  391.                         $loops[$k][] = &$pathInLoop;
  392.                         $loopByConstructor $loopByConstructor && $pathByConstructor;
  393.                     } elseif ($k === $id) {
  394.                         $loop = [];
  395.                     }
  396.                 }
  397.                 $this->addCircularReferences($id$loop$loopByConstructor);
  398.             } elseif (!isset($checkedNodes[$id])) {
  399.                 $this->collectCircularReferences($id$node->getOutEdges(), $checkedNodes$loops$path$edge->isReferencedByConstructor());
  400.             } elseif (isset($loops[$id])) {
  401.                 // we already had detected loops for this edge
  402.                 // let's check if we have a common ancestor in one of the detected loops
  403.                 foreach ($loops[$id] as [$first$loopPath]) {
  404.                     if (!isset($path[$first])) {
  405.                         continue;
  406.                     }
  407.                     // We have a common ancestor, let's fill the current path
  408.                     $fillPath null;
  409.                     foreach ($loopPath as $k => $pathByConstructor) {
  410.                         if (null !== $fillPath) {
  411.                             $fillPath[$k] = $pathByConstructor;
  412.                         } elseif ($k === $id) {
  413.                             $fillPath $path;
  414.                             $fillPath[$k] = $pathByConstructor;
  415.                         }
  416.                     }
  417.                     // we can now build the loop
  418.                     $loop null;
  419.                     $loopByConstructor $edge->isReferencedByConstructor();
  420.                     foreach ($fillPath as $k => $pathByConstructor) {
  421.                         if (null !== $loop) {
  422.                             $loop[] = $k;
  423.                             $loopByConstructor $loopByConstructor && $pathByConstructor;
  424.                         } elseif ($k === $first) {
  425.                             $loop = [];
  426.                         }
  427.                     }
  428.                     $this->addCircularReferences($first$looptrue);
  429.                     break;
  430.                 }
  431.             }
  432.         }
  433.         unset($path[$sourceId]);
  434.     }
  435.     private function addCircularReferences(string $sourceId, array $currentPathbool $byConstructor)
  436.     {
  437.         $currentId $sourceId;
  438.         $currentPath array_reverse($currentPath);
  439.         $currentPath[] = $currentId;
  440.         foreach ($currentPath as $parentId) {
  441.             if (empty($this->circularReferences[$parentId][$currentId])) {
  442.                 $this->circularReferences[$parentId][$currentId] = $byConstructor;
  443.             }
  444.             $currentId $parentId;
  445.         }
  446.     }
  447.     private function collectLineage(string $class, array &$lineage)
  448.     {
  449.         if (isset($lineage[$class])) {
  450.             return;
  451.         }
  452.         if (!$r $this->container->getReflectionClass($classfalse)) {
  453.             return;
  454.         }
  455.         if (is_a($class$this->baseClasstrue)) {
  456.             return;
  457.         }
  458.         $file $r->getFileName();
  459.         if (str_ends_with($file') : eval()\'d code')) {
  460.             $file substr($file0strrpos($file'(', -17));
  461.         }
  462.         if (!$file || $this->doExport($file) === $exportedFile $this->export($file)) {
  463.             return;
  464.         }
  465.         $lineage[$class] = substr($exportedFile1, -1);
  466.         if ($parent $r->getParentClass()) {
  467.             $this->collectLineage($parent->name$lineage);
  468.         }
  469.         foreach ($r->getInterfaces() as $parent) {
  470.             $this->collectLineage($parent->name$lineage);
  471.         }
  472.         foreach ($r->getTraits() as $parent) {
  473.             $this->collectLineage($parent->name$lineage);
  474.         }
  475.         unset($lineage[$class]);
  476.         $lineage[$class] = substr($exportedFile1, -1);
  477.     }
  478.     private function generateProxyClasses(): array
  479.     {
  480.         $proxyClasses = [];
  481.         $alreadyGenerated = [];
  482.         $definitions $this->container->getDefinitions();
  483.         $strip '' === $this->docStar && method_exists(Kernel::class, 'stripComments');
  484.         $proxyDumper $this->getProxyDumper();
  485.         ksort($definitions);
  486.         foreach ($definitions as $definition) {
  487.             if (!$proxyDumper->isProxyCandidate($definition)) {
  488.                 continue;
  489.             }
  490.             if (isset($alreadyGenerated[$class $definition->getClass()])) {
  491.                 continue;
  492.             }
  493.             $alreadyGenerated[$class] = true;
  494.             // register class' reflector for resource tracking
  495.             $this->container->getReflectionClass($class);
  496.             if ("\n" === $proxyCode "\n".$proxyDumper->getProxyCode($definition)) {
  497.                 continue;
  498.             }
  499.             if ($this->inlineRequires) {
  500.                 $lineage = [];
  501.                 $this->collectLineage($class$lineage);
  502.                 $code '';
  503.                 foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) {
  504.                     if ($this->inlineFactories) {
  505.                         $this->inlinedRequires[$file] = true;
  506.                     }
  507.                     $code .= sprintf("include_once %s;\n"$file);
  508.                 }
  509.                 $proxyCode $code.$proxyCode;
  510.             }
  511.             if ($strip) {
  512.                 $proxyCode "<?php\n".$proxyCode;
  513.                 $proxyCode substr(Kernel::stripComments($proxyCode), 5);
  514.             }
  515.             $proxyClass explode(' '$this->inlineRequires substr($proxyCode, \strlen($code)) : $proxyCode3)[1];
  516.             if ($this->asFiles || $this->namespace) {
  517.                 $proxyCode .= "\nif (!\\class_exists('$proxyClass', false)) {\n    \\class_alias(__NAMESPACE__.'\\\\$proxyClass', '$proxyClass', false);\n}\n";
  518.             }
  519.             $proxyClasses[$proxyClass.'.php'] = $proxyCode;
  520.         }
  521.         return $proxyClasses;
  522.     }
  523.     private function addServiceInclude(string $cIdDefinition $definition): string
  524.     {
  525.         $code '';
  526.         if ($this->inlineRequires && (!$this->isHotPath($definition) || $this->getProxyDumper()->isProxyCandidate($definition))) {
  527.             $lineage = [];
  528.             foreach ($this->inlinedDefinitions as $def) {
  529.                 if (!$def->isDeprecated()) {
  530.                     foreach ($this->getClasses($def$cId) as $class) {
  531.                         $this->collectLineage($class$lineage);
  532.                     }
  533.                 }
  534.             }
  535.             foreach ($this->serviceCalls as $id => [$callCount$behavior]) {
  536.                 if ('service_container' !== $id && $id !== $cId
  537.                     && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior
  538.                     && $this->container->has($id)
  539.                     && $this->isTrivialInstance($def $this->container->findDefinition($id))
  540.                 ) {
  541.                     foreach ($this->getClasses($def$cId) as $class) {
  542.                         $this->collectLineage($class$lineage);
  543.                     }
  544.                 }
  545.             }
  546.             foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) {
  547.                 $code .= sprintf("        include_once %s;\n"$file);
  548.             }
  549.         }
  550.         foreach ($this->inlinedDefinitions as $def) {
  551.             if ($file $def->getFile()) {
  552.                 $file $this->dumpValue($file);
  553.                 $file '(' === $file[0] ? substr($file1, -1) : $file;
  554.                 $code .= sprintf("        include_once %s;\n"$file);
  555.             }
  556.         }
  557.         if ('' !== $code) {
  558.             $code .= "\n";
  559.         }
  560.         return $code;
  561.     }
  562.     /**
  563.      * @throws InvalidArgumentException
  564.      * @throws RuntimeException
  565.      */
  566.     private function addServiceInstance(string $idDefinition $definitionbool $isSimpleInstance): string
  567.     {
  568.         $class $this->dumpValue($definition->getClass());
  569.         if (str_starts_with($class"'") && !str_contains($class'$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/'$class)) {
  570.             throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.'$class$id));
  571.         }
  572.         $isProxyCandidate $this->getProxyDumper()->isProxyCandidate($definition);
  573.         $instantiation '';
  574.         $lastWitherIndex null;
  575.         foreach ($definition->getMethodCalls() as $k => $call) {
  576.             if ($call[2] ?? false) {
  577.                 $lastWitherIndex $k;
  578.             }
  579.         }
  580.         if (!$isProxyCandidate && $definition->isShared() && !isset($this->singleUsePrivateIds[$id]) && null === $lastWitherIndex) {
  581.             $instantiation sprintf('$this->%s[%s] = %s'$this->container->getDefinition($id)->isPublic() ? 'services' 'privates'$this->doExport($id), $isSimpleInstance '' '$instance');
  582.         } elseif (!$isSimpleInstance) {
  583.             $instantiation '$instance';
  584.         }
  585.         $return '';
  586.         if ($isSimpleInstance) {
  587.             $return 'return ';
  588.         } else {
  589.             $instantiation .= ' = ';
  590.         }
  591.         return $this->addNewInstance($definition'        '.$return.$instantiation$id);
  592.     }
  593.     private function isTrivialInstance(Definition $definition): bool
  594.     {
  595.         if ($definition->hasErrors()) {
  596.             return true;
  597.         }
  598.         if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) {
  599.             return false;
  600.         }
  601.         if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || < \count($definition->getArguments())) {
  602.             return false;
  603.         }
  604.         foreach ($definition->getArguments() as $arg) {
  605.             if (!$arg || $arg instanceof Parameter) {
  606.                 continue;
  607.             }
  608.             if (\is_array($arg) && >= \count($arg)) {
  609.                 foreach ($arg as $k => $v) {
  610.                     if ($this->dumpValue($k) !== $this->dumpValue($kfalse)) {
  611.                         return false;
  612.                     }
  613.                     if (!$v || $v instanceof Parameter) {
  614.                         continue;
  615.                     }
  616.                     if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) {
  617.                         continue;
  618.                     }
  619.                     if (!\is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($vfalse)) {
  620.                         return false;
  621.                     }
  622.                 }
  623.             } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) {
  624.                 continue;
  625.             } elseif (!\is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($argfalse)) {
  626.                 return false;
  627.             }
  628.         }
  629.         return true;
  630.     }
  631.     private function addServiceMethodCalls(Definition $definitionstring $variableName, ?string $sharedNonLazyId): string
  632.     {
  633.         $lastWitherIndex null;
  634.         foreach ($definition->getMethodCalls() as $k => $call) {
  635.             if ($call[2] ?? false) {
  636.                 $lastWitherIndex $k;
  637.             }
  638.         }
  639.         $calls '';
  640.         foreach ($definition->getMethodCalls() as $k => $call) {
  641.             $arguments = [];
  642.             foreach ($call[1] as $i => $value) {
  643.                 $arguments[] = (\is_string($i) ? $i.': ' '').$this->dumpValue($value);
  644.             }
  645.             $witherAssignation '';
  646.             if ($call[2] ?? false) {
  647.                 if (null !== $sharedNonLazyId && $lastWitherIndex === $k) {
  648.                     $witherAssignation sprintf('$this->%s[\'%s\'] = '$definition->isPublic() ? 'services' 'privates'$sharedNonLazyId);
  649.                 }
  650.                 $witherAssignation .= sprintf('$%s = '$variableName);
  651.             }
  652.             $calls .= $this->wrapServiceConditionals($call[1], sprintf("        %s\$%s->%s(%s);\n"$witherAssignation$variableName$call[0], implode(', '$arguments)));
  653.         }
  654.         return $calls;
  655.     }
  656.     private function addServiceProperties(Definition $definitionstring $variableName 'instance'): string
  657.     {
  658.         $code '';
  659.         foreach ($definition->getProperties() as $name => $value) {
  660.             $code .= sprintf("        \$%s->%s = %s;\n"$variableName$name$this->dumpValue($value));
  661.         }
  662.         return $code;
  663.     }
  664.     private function addServiceConfigurator(Definition $definitionstring $variableName 'instance'): string
  665.     {
  666.         if (!$callable $definition->getConfigurator()) {
  667.             return '';
  668.         }
  669.         if (\is_array($callable)) {
  670.             if ($callable[0] instanceof Reference
  671.                 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))
  672.             ) {
  673.                 return sprintf("        %s->%s(\$%s);\n"$this->dumpValue($callable[0]), $callable[1], $variableName);
  674.             }
  675.             $class $this->dumpValue($callable[0]);
  676.             // If the class is a string we can optimize away
  677.             if (str_starts_with($class"'") && !str_contains($class'$')) {
  678.                 return sprintf("        %s::%s(\$%s);\n"$this->dumpLiteralClass($class), $callable[1], $variableName);
  679.             }
  680.             if (str_starts_with($class'new ')) {
  681.                 return sprintf("        (%s)->%s(\$%s);\n"$this->dumpValue($callable[0]), $callable[1], $variableName);
  682.             }
  683.             return sprintf("        [%s, '%s'](\$%s);\n"$this->dumpValue($callable[0]), $callable[1], $variableName);
  684.         }
  685.         return sprintf("        %s(\$%s);\n"$callable$variableName);
  686.     }
  687.     private function addService(string $idDefinition $definition): array
  688.     {
  689.         $this->definitionVariables = new \SplObjectStorage();
  690.         $this->referenceVariables = [];
  691.         $this->variableCount 0;
  692.         $this->referenceVariables[$id] = new Variable('instance');
  693.         $return = [];
  694.         if ($class $definition->getClass()) {
  695.             $class $class instanceof Parameter '%'.$class.'%' $this->container->resolveEnvPlaceholders($class);
  696.             $return[] = sprintf(str_starts_with($class'%') ? '@return object A %1$s instance' '@return \%s'ltrim($class'\\'));
  697.         } elseif ($definition->getFactory()) {
  698.             $factory $definition->getFactory();
  699.             if (\is_string($factory)) {
  700.                 $return[] = sprintf('@return object An instance returned by %s()'$factory);
  701.             } elseif (\is_array($factory) && (\is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
  702.                 $class $factory[0] instanceof Definition $factory[0]->getClass() : (string) $factory[0];
  703.                 $class $class instanceof Parameter '%'.$class.'%' $this->container->resolveEnvPlaceholders($class);
  704.                 $return[] = sprintf('@return object An instance returned by %s::%s()'$class$factory[1]);
  705.             }
  706.         }
  707.         if ($definition->isDeprecated()) {
  708.             if ($return && str_starts_with($return[\count($return) - 1], '@return')) {
  709.                 $return[] = '';
  710.             }
  711.             $deprecation $definition->getDeprecation($id);
  712.             $return[] = sprintf('@deprecated %s', ($deprecation['package'] || $deprecation['version'] ? "Since {$deprecation['package']} {$deprecation['version']}: " '').$deprecation['message']);
  713.         }
  714.         $return str_replace("\n     * \n""\n     *\n"implode("\n     * "$return));
  715.         $return $this->container->resolveEnvPlaceholders($return);
  716.         $shared $definition->isShared() ? ' shared' '';
  717.         $public $definition->isPublic() ? 'public' 'private';
  718.         $autowired $definition->isAutowired() ? ' autowired' '';
  719.         $asFile $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition);
  720.         $methodName $this->generateMethodName($id);
  721.         if ($asFile || $definition->isLazy()) {
  722.             $lazyInitialization '$lazyLoad = true';
  723.         } else {
  724.             $lazyInitialization '';
  725.         }
  726.         $code = <<<EOF
  727.     /*{$this->docStar}
  728.      * Gets the $public '$id'$shared$autowired service.
  729.      *
  730.      * $return
  731. EOF;
  732.         $code str_replace('*/'' '$code).<<<EOF
  733.      */
  734.     protected function {$methodName}($lazyInitialization)
  735.     {
  736. EOF;
  737.         if ($asFile) {
  738.             $file $methodName.'.php';
  739.             $code str_replace("protected function {$methodName}("'public static function do($container, '$code);
  740.         } else {
  741.             $file null;
  742.         }
  743.         if ($definition->hasErrors() && $e $definition->getErrors()) {
  744.             $this->addThrow true;
  745.             $code .= sprintf("        \$this->throw(%s);\n"$this->export(reset($e)));
  746.         } else {
  747.             $this->serviceCalls = [];
  748.             $this->inlinedDefinitions $this->getDefinitionsFromArguments([$definition], null$this->serviceCalls);
  749.             if ($definition->isDeprecated()) {
  750.                 $deprecation $definition->getDeprecation($id);
  751.                 $code .= sprintf("        trigger_deprecation(%s, %s, %s);\n\n"$this->export($deprecation['package']), $this->export($deprecation['version']), $this->export($deprecation['message']));
  752.             } elseif ($definition->hasTag($this->hotPathTag) || !$definition->hasTag($this->preloadTags[1])) {
  753.                 foreach ($this->inlinedDefinitions as $def) {
  754.                     foreach ($this->getClasses($def$id) as $class) {
  755.                         $this->preload[$class] = $class;
  756.                     }
  757.                 }
  758.             }
  759.             if (!$definition->isShared()) {
  760.                 $factory sprintf('$this->factories%s[%s]'$definition->isPublic() ? '' "['service_container']"$this->doExport($id));
  761.             }
  762.             if ($isProxyCandidate $this->getProxyDumper()->isProxyCandidate($definition)) {
  763.                 if (!$definition->isShared()) {
  764.                     $code .= sprintf('        %s = %1$s ?? '$factory);
  765.                     if ($asFile) {
  766.                         $code .= "function () {\n";
  767.                         $code .= "            return self::do(\$container);\n";
  768.                         $code .= "        };\n\n";
  769.                     } else {
  770.                         $code .= sprintf("\\Closure::fromCallable([\$this, '%s']);\n\n"$methodName);
  771.                     }
  772.                 }
  773.                 $factoryCode $asFile 'self::do($container, false)' sprintf('$this->%s(false)'$methodName);
  774.                 $factoryCode $this->getProxyDumper()->getProxyFactoryCode($definition$id$factoryCode);
  775.                 $code .= $asFile preg_replace('/function \(([^)]*+)\)( {|:)/''function (\1) use ($container)\2'$factoryCode) : $factoryCode;
  776.             }
  777.             $c $this->addServiceInclude($id$definition);
  778.             if ('' !== $c && $isProxyCandidate && !$definition->isShared()) {
  779.                 $c implode("\n"array_map(function ($line) { return $line '    '.$line $line; }, explode("\n"$c)));
  780.                 $code .= "        static \$include = true;\n\n";
  781.                 $code .= "        if (\$include) {\n";
  782.                 $code .= $c;
  783.                 $code .= "            \$include = false;\n";
  784.                 $code .= "        }\n\n";
  785.             } else {
  786.                 $code .= $c;
  787.             }
  788.             $c $this->addInlineService($id$definition);
  789.             if (!$isProxyCandidate && !$definition->isShared()) {
  790.                 $c implode("\n"array_map(function ($line) { return $line '    '.$line $line; }, explode("\n"$c)));
  791.                 $lazyloadInitialization $definition->isLazy() ? '$lazyLoad = true' '';
  792.                 $c sprintf("        %s = function (%s) {\n%s        };\n\n        return %1\$s();\n"$factory$lazyloadInitialization$c);
  793.             }
  794.             $code .= $c;
  795.         }
  796.         if ($asFile) {
  797.             $code str_replace('$this''$container'$code);
  798.             $code preg_replace('/function \(([^)]*+)\)( {|:)/''function (\1) use ($container)\2'$code);
  799.         }
  800.         $code .= "    }\n";
  801.         $this->definitionVariables $this->inlinedDefinitions null;
  802.         $this->referenceVariables $this->serviceCalls null;
  803.         return [$file$code];
  804.     }
  805.     private function addInlineVariables(string $idDefinition $definition, array $argumentsbool $forConstructor): string
  806.     {
  807.         $code '';
  808.         foreach ($arguments as $argument) {
  809.             if (\is_array($argument)) {
  810.                 $code .= $this->addInlineVariables($id$definition$argument$forConstructor);
  811.             } elseif ($argument instanceof Reference) {
  812.                 $code .= $this->addInlineReference($id$definition$argument$forConstructor);
  813.             } elseif ($argument instanceof Definition) {
  814.                 $code .= $this->addInlineService($id$definition$argument$forConstructor);
  815.             }
  816.         }
  817.         return $code;
  818.     }
  819.     private function addInlineReference(string $idDefinition $definitionstring $targetIdbool $forConstructor): string
  820.     {
  821.         while ($this->container->hasAlias($targetId)) {
  822.             $targetId = (string) $this->container->getAlias($targetId);
  823.         }
  824.         [$callCount$behavior] = $this->serviceCalls[$targetId];
  825.         if ($id === $targetId) {
  826.             return $this->addInlineService($id$definition$definition);
  827.         }
  828.         if ('service_container' === $targetId || isset($this->referenceVariables[$targetId])) {
  829.             return '';
  830.         }
  831.         if ($this->container->hasDefinition($targetId) && ($def $this->container->getDefinition($targetId)) && !$def->isShared()) {
  832.             return '';
  833.         }
  834.         $hasSelfRef = isset($this->circularReferences[$id][$targetId]) && !isset($this->definitionVariables[$definition]);
  835.         if ($hasSelfRef && !$forConstructor && !$forConstructor = !$this->circularReferences[$id][$targetId]) {
  836.             $code $this->addInlineService($id$definition$definition);
  837.         } else {
  838.             $code '';
  839.         }
  840.         if (isset($this->referenceVariables[$targetId]) || ($callCount && (!$hasSelfRef || !$forConstructor))) {
  841.             return $code;
  842.         }
  843.         $name $this->getNextVariableName();
  844.         $this->referenceVariables[$targetId] = new Variable($name);
  845.         $reference ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $behavior ? new Reference($targetId$behavior) : null;
  846.         $code .= sprintf("        \$%s = %s;\n"$name$this->getServiceCall($targetId$reference));
  847.         if (!$hasSelfRef || !$forConstructor) {
  848.             return $code;
  849.         }
  850.         $code .= sprintf(<<<'EOTXT'
  851.         if (isset($this->%s[%s])) {
  852.             return $this->%1$s[%2$s];
  853.         }
  854. EOTXT
  855.             ,
  856.             $this->container->getDefinition($id)->isPublic() ? 'services' 'privates',
  857.             $this->doExport($id)
  858.         );
  859.         return $code;
  860.     }
  861.     private function addInlineService(string $idDefinition $definitionDefinition $inlineDef nullbool $forConstructor true): string
  862.     {
  863.         $code '';
  864.         if ($isSimpleInstance $isRootInstance null === $inlineDef) {
  865.             foreach ($this->serviceCalls as $targetId => [$callCount$behavior$byConstructor]) {
  866.                 if ($byConstructor && isset($this->circularReferences[$id][$targetId]) && !$this->circularReferences[$id][$targetId]) {
  867.                     $code .= $this->addInlineReference($id$definition$targetId$forConstructor);
  868.                 }
  869.             }
  870.         }
  871.         if (isset($this->definitionVariables[$inlineDef $inlineDef ?: $definition])) {
  872.             return $code;
  873.         }
  874.         $arguments = [$inlineDef->getArguments(), $inlineDef->getFactory()];
  875.         $code .= $this->addInlineVariables($id$definition$arguments$forConstructor);
  876.         if ($arguments array_filter([$inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()])) {
  877.             $isSimpleInstance false;
  878.         } elseif ($definition !== $inlineDef && $this->inlinedDefinitions[$inlineDef]) {
  879.             return $code;
  880.         }
  881.         if (isset($this->definitionVariables[$inlineDef])) {
  882.             $isSimpleInstance false;
  883.         } else {
  884.             $name $definition === $inlineDef 'instance' $this->getNextVariableName();
  885.             $this->definitionVariables[$inlineDef] = new Variable($name);
  886.             $code .= '' !== $code "\n" '';
  887.             if ('instance' === $name) {
  888.                 $code .= $this->addServiceInstance($id$definition$isSimpleInstance);
  889.             } else {
  890.                 $code .= $this->addNewInstance($inlineDef'        $'.$name.' = '$id);
  891.             }
  892.             if ('' !== $inline $this->addInlineVariables($id$definition$argumentsfalse)) {
  893.                 $code .= "\n".$inline."\n";
  894.             } elseif ($arguments && 'instance' === $name) {
  895.                 $code .= "\n";
  896.             }
  897.             $code .= $this->addServiceProperties($inlineDef$name);
  898.             $code .= $this->addServiceMethodCalls($inlineDef$name, !$this->getProxyDumper()->isProxyCandidate($inlineDef) && $inlineDef->isShared() && !isset($this->singleUsePrivateIds[$id]) ? $id null);
  899.             $code .= $this->addServiceConfigurator($inlineDef$name);
  900.         }
  901.         if ($isRootInstance && !$isSimpleInstance) {
  902.             $code .= "\n        return \$instance;\n";
  903.         }
  904.         return $code;
  905.     }
  906.     private function addServices(array &$services null): string
  907.     {
  908.         $publicServices $privateServices '';
  909.         $definitions $this->container->getDefinitions();
  910.         ksort($definitions);
  911.         foreach ($definitions as $id => $definition) {
  912.             if (!$definition->isSynthetic()) {
  913.                 $services[$id] = $this->addService($id$definition);
  914.             } elseif ($definition->hasTag($this->hotPathTag) || !$definition->hasTag($this->preloadTags[1])) {
  915.                 $services[$id] = null;
  916.                 foreach ($this->getClasses($definition$id) as $class) {
  917.                     $this->preload[$class] = $class;
  918.                 }
  919.             }
  920.         }
  921.         foreach ($definitions as $id => $definition) {
  922.             if (!([$file$code] = $services[$id]) || null !== $file) {
  923.                 continue;
  924.             }
  925.             if ($definition->isPublic()) {
  926.                 $publicServices .= $code;
  927.             } elseif (!$this->isTrivialInstance($definition) || isset($this->locatedIds[$id])) {
  928.                 $privateServices .= $code;
  929.             }
  930.         }
  931.         return $publicServices.$privateServices;
  932.     }
  933.     private function generateServiceFiles(array $services): iterable
  934.     {
  935.         $definitions $this->container->getDefinitions();
  936.         ksort($definitions);
  937.         foreach ($definitions as $id => $definition) {
  938.             if (([$file$code] = $services[$id]) && null !== $file && ($definition->isPublic() || !$this->isTrivialInstance($definition) || isset($this->locatedIds[$id]))) {
  939.                 yield $file => [$code$definition->hasTag($this->hotPathTag) || !$definition->hasTag($this->preloadTags[1]) && !$definition->isDeprecated() && !$definition->hasErrors()];
  940.             }
  941.         }
  942.     }
  943.     private function addNewInstance(Definition $definitionstring $return ''string $id null): string
  944.     {
  945.         $tail $return ";\n" '';
  946.         if (BaseServiceLocator::class === $definition->getClass() && $definition->hasTag($this->serviceLocatorTag)) {
  947.             $arguments = [];
  948.             foreach ($definition->getArgument(0) as $k => $argument) {
  949.                 $arguments[$k] = $argument->getValues()[0];
  950.             }
  951.             return $return.$this->dumpValue(new ServiceLocatorArgument($arguments)).$tail;
  952.         }
  953.         $arguments = [];
  954.         foreach ($definition->getArguments() as $i => $value) {
  955.             $arguments[] = (\is_string($i) ? $i.': ' '').$this->dumpValue($value);
  956.         }
  957.         if (null !== $definition->getFactory()) {
  958.             $callable $definition->getFactory();
  959.             if (\is_array($callable)) {
  960.                 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/'$callable[1])) {
  961.                     throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s).'$callable[1] ?: 'n/a'));
  962.                 }
  963.                 if ($callable[0] instanceof Reference
  964.                     || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
  965.                     return $return.sprintf('%s->%s(%s)'$this->dumpValue($callable[0]), $callable[1], $arguments implode(', '$arguments) : '').$tail;
  966.                 }
  967.                 $class $this->dumpValue($callable[0]);
  968.                 // If the class is a string we can optimize away
  969.                 if (str_starts_with($class"'") && !str_contains($class'$')) {
  970.                     if ("''" === $class) {
  971.                         throw new RuntimeException(sprintf('Cannot dump definition: "%s" service is defined to be created by a factory but is missing the service reference, did you forget to define the factory service id or class?'$id 'The "'.$id.'"' 'inline'));
  972.                     }
  973.                     return $return.sprintf('%s::%s(%s)'$this->dumpLiteralClass($class), $callable[1], $arguments implode(', '$arguments) : '').$tail;
  974.                 }
  975.                 if (str_starts_with($class'new ')) {
  976.                     return $return.sprintf('(%s)->%s(%s)'$class$callable[1], $arguments implode(', '$arguments) : '').$tail;
  977.                 }
  978.                 return $return.sprintf("[%s, '%s'](%s)"$class$callable[1], $arguments implode(', '$arguments) : '').$tail;
  979.             }
  980.             return $return.sprintf('%s(%s)'$this->dumpLiteralClass($this->dumpValue($callable)), $arguments implode(', '$arguments) : '').$tail;
  981.         }
  982.         if (null === $class $definition->getClass()) {
  983.             throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
  984.         }
  985.         return $return.sprintf('new %s(%s)'$this->dumpLiteralClass($this->dumpValue($class)), implode(', '$arguments)).$tail;
  986.     }
  987.     private function startClass(string $classstring $baseClassbool $hasProxyClasses): string
  988.     {
  989.         $namespaceLine = !$this->asFiles && $this->namespace "\nnamespace {$this->namespace};\n" '';
  990.         $code = <<<EOF
  991. <?php
  992. $namespaceLine
  993. use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
  994. use Symfony\Component\DependencyInjection\ContainerInterface;
  995. use Symfony\Component\DependencyInjection\Container;
  996. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  997. use Symfony\Component\DependencyInjection\Exception\LogicException;
  998. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  999. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  1000. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  1001. /*{$this->docStar}
  1002.  * @internal This class has been auto-generated by the Symfony Dependency Injection Component.
  1003.  */
  1004. class $class extends $baseClass
  1005. {
  1006.     protected \$parameters = [];
  1007.     public function __construct()
  1008.     {
  1009. EOF;
  1010.         if ($this->asFiles) {
  1011.             $code str_replace('$parameters = []'"\$containerDir;\n    protected \$parameters = [];\n    private \$buildParameters"$code);
  1012.             $code str_replace('__construct()''__construct(array $buildParameters = [], $containerDir = __DIR__)'$code);
  1013.             $code .= "        \$this->buildParameters = \$buildParameters;\n";
  1014.             $code .= "        \$this->containerDir = \$containerDir;\n";
  1015.             if (null !== $this->targetDirRegex) {
  1016.                 $code str_replace('$parameters = []'"\$targetDir;\n    protected \$parameters = []"$code);
  1017.                 $code .= '        $this->targetDir = \\dirname($containerDir);'."\n";
  1018.             }
  1019.         }
  1020.         if (Container::class !== $this->baseClass) {
  1021.             $r $this->container->getReflectionClass($this->baseClassfalse);
  1022.             if (null !== $r
  1023.                 && (null !== $constructor $r->getConstructor())
  1024.                 && === $constructor->getNumberOfRequiredParameters()
  1025.                 && Container::class !== $constructor->getDeclaringClass()->name
  1026.             ) {
  1027.                 $code .= "        parent::__construct();\n";
  1028.                 $code .= "        \$this->parameterBag = null;\n\n";
  1029.             }
  1030.         }
  1031.         if ($this->container->getParameterBag()->all()) {
  1032.             $code .= "        \$this->parameters = \$this->getDefaultParameters();\n\n";
  1033.         }
  1034.         $code .= "        \$this->services = \$this->privates = [];\n";
  1035.         $code .= $this->addSyntheticIds();
  1036.         $code .= $this->addMethodMap();
  1037.         $code .= $this->asFiles && !$this->inlineFactories $this->addFileMap() : '';
  1038.         $code .= $this->addAliases();
  1039.         $code .= $this->addInlineRequires($hasProxyClasses);
  1040.         $code .= <<<EOF
  1041.     }
  1042.     public function compile(): void
  1043.     {
  1044.         throw new LogicException('You cannot compile a dumped container that was already compiled.');
  1045.     }
  1046.     public function isCompiled(): bool
  1047.     {
  1048.         return true;
  1049.     }
  1050. EOF;
  1051.         $code .= $this->addRemovedIds();
  1052.         if ($this->asFiles && !$this->inlineFactories) {
  1053.             $code .= <<<'EOF'
  1054.     protected function load($file, $lazyLoad = true)
  1055.     {
  1056.         if (class_exists($class = __NAMESPACE__.'\\'.$file, false)) {
  1057.             return $class::do($this, $lazyLoad);
  1058.         }
  1059.         if ('.' === $file[-4]) {
  1060.             $class = substr($class, 0, -4);
  1061.         } else {
  1062.             $file .= '.php';
  1063.         }
  1064.         $service = require $this->containerDir.\DIRECTORY_SEPARATOR.$file;
  1065.         return class_exists($class, false) ? $class::do($this, $lazyLoad) : $service;
  1066.     }
  1067. EOF;
  1068.         }
  1069.         $proxyDumper $this->getProxyDumper();
  1070.         foreach ($this->container->getDefinitions() as $definition) {
  1071.             if (!$proxyDumper->isProxyCandidate($definition)) {
  1072.                 continue;
  1073.             }
  1074.             if ($this->asFiles && !$this->inlineFactories) {
  1075.                 $proxyLoader "class_exists(\$class, false) || require __DIR__.'/'.\$class.'.php';\n\n        ";
  1076.             } else {
  1077.                 $proxyLoader '';
  1078.             }
  1079.             $code .= <<<EOF
  1080.     protected function createProxy(\$class, \Closure \$factory)
  1081.     {
  1082.         {$proxyLoader}return \$factory();
  1083.     }
  1084. EOF;
  1085.             break;
  1086.         }
  1087.         return $code;
  1088.     }
  1089.     private function addSyntheticIds(): string
  1090.     {
  1091.         $code '';
  1092.         $definitions $this->container->getDefinitions();
  1093.         ksort($definitions);
  1094.         foreach ($definitions as $id => $definition) {
  1095.             if ($definition->isSynthetic() && 'service_container' !== $id) {
  1096.                 $code .= '            '.$this->doExport($id)." => true,\n";
  1097.             }
  1098.         }
  1099.         return $code "        \$this->syntheticIds = [\n{$code}        ];\n" '';
  1100.     }
  1101.     private function addRemovedIds(): string
  1102.     {
  1103.         $ids $this->container->getRemovedIds();
  1104.         foreach ($this->container->getDefinitions() as $id => $definition) {
  1105.             if (!$definition->isPublic()) {
  1106.                 $ids[$id] = true;
  1107.             }
  1108.         }
  1109.         if (!$ids) {
  1110.             return '';
  1111.         }
  1112.         if ($this->asFiles) {
  1113.             $code "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'";
  1114.         } else {
  1115.             $code '';
  1116.             $ids array_keys($ids);
  1117.             sort($ids);
  1118.             foreach ($ids as $id) {
  1119.                 if (preg_match(FileLoader::ANONYMOUS_ID_REGEXP$id)) {
  1120.                     continue;
  1121.                 }
  1122.                 $code .= '            '.$this->doExport($id)." => true,\n";
  1123.             }
  1124.             $code "[\n{$code}        ]";
  1125.         }
  1126.         return <<<EOF
  1127.     public function getRemovedIds(): array
  1128.     {
  1129.         return {$code};
  1130.     }
  1131. EOF;
  1132.     }
  1133.     private function addMethodMap(): string
  1134.     {
  1135.         $code '';
  1136.         $definitions $this->container->getDefinitions();
  1137.         ksort($definitions);
  1138.         foreach ($definitions as $id => $definition) {
  1139.             if (!$definition->isSynthetic() && $definition->isPublic() && (!$this->asFiles || $this->inlineFactories || $this->isHotPath($definition))) {
  1140.                 $code .= '            '.$this->doExport($id).' => '.$this->doExport($this->generateMethodName($id)).",\n";
  1141.             }
  1142.         }
  1143.         $aliases $this->container->getAliases();
  1144.         foreach ($aliases as $alias => $id) {
  1145.             if (!$id->isDeprecated()) {
  1146.                 continue;
  1147.             }
  1148.             $code .= '            '.$this->doExport($alias).' => '.$this->doExport($this->generateMethodName($alias)).",\n";
  1149.         }
  1150.         return $code "        \$this->methodMap = [\n{$code}        ];\n" '';
  1151.     }
  1152.     private function addFileMap(): string
  1153.     {
  1154.         $code '';
  1155.         $definitions $this->container->getDefinitions();
  1156.         ksort($definitions);
  1157.         foreach ($definitions as $id => $definition) {
  1158.             if (!$definition->isSynthetic() && $definition->isPublic() && !$this->isHotPath($definition)) {
  1159.                 $code .= sprintf("            %s => '%s',\n"$this->doExport($id), $this->generateMethodName($id));
  1160.             }
  1161.         }
  1162.         return $code "        \$this->fileMap = [\n{$code}        ];\n" '';
  1163.     }
  1164.     private function addAliases(): string
  1165.     {
  1166.         if (!$aliases $this->container->getAliases()) {
  1167.             return "\n        \$this->aliases = [];\n";
  1168.         }
  1169.         $code "        \$this->aliases = [\n";
  1170.         ksort($aliases);
  1171.         foreach ($aliases as $alias => $id) {
  1172.             if ($id->isDeprecated()) {
  1173.                 continue;
  1174.             }
  1175.             $id = (string) $id;
  1176.             while (isset($aliases[$id])) {
  1177.                 $id = (string) $aliases[$id];
  1178.             }
  1179.             $code .= '            '.$this->doExport($alias).' => '.$this->doExport($id).",\n";
  1180.         }
  1181.         return $code."        ];\n";
  1182.     }
  1183.     private function addDeprecatedAliases(): string
  1184.     {
  1185.         $code '';
  1186.         $aliases $this->container->getAliases();
  1187.         foreach ($aliases as $alias => $definition) {
  1188.             if (!$definition->isDeprecated()) {
  1189.                 continue;
  1190.             }
  1191.             $public $definition->isPublic() ? 'public' 'private';
  1192.             $id = (string) $definition;
  1193.             $methodNameAlias $this->generateMethodName($alias);
  1194.             $idExported $this->export($id);
  1195.             $deprecation $definition->getDeprecation($alias);
  1196.             $packageExported $this->export($deprecation['package']);
  1197.             $versionExported $this->export($deprecation['version']);
  1198.             $messageExported $this->export($deprecation['message']);
  1199.             $code .= <<<EOF
  1200.     /*{$this->docStar}
  1201.      * Gets the $public '$alias' alias.
  1202.      *
  1203.      * @return object The "$id" service.
  1204.      */
  1205.     protected function {$methodNameAlias}()
  1206.     {
  1207.         trigger_deprecation($packageExported$versionExported$messageExported);
  1208.         return \$this->get($idExported);
  1209.     }
  1210. EOF;
  1211.         }
  1212.         return $code;
  1213.     }
  1214.     private function addInlineRequires(bool $hasProxyClasses): string
  1215.     {
  1216.         $lineage = [];
  1217.         $hotPathServices $this->hotPathTag && $this->inlineRequires $this->container->findTaggedServiceIds($this->hotPathTag) : [];
  1218.         foreach ($hotPathServices as $id => $tags) {
  1219.             $definition $this->container->getDefinition($id);
  1220.             if ($this->getProxyDumper()->isProxyCandidate($definition)) {
  1221.                 continue;
  1222.             }
  1223.             $inlinedDefinitions $this->getDefinitionsFromArguments([$definition]);
  1224.             foreach ($inlinedDefinitions as $def) {
  1225.                 foreach ($this->getClasses($def$id) as $class) {
  1226.                     $this->collectLineage($class$lineage);
  1227.                 }
  1228.             }
  1229.         }
  1230.         $code '';
  1231.         foreach ($lineage as $file) {
  1232.             if (!isset($this->inlinedRequires[$file])) {
  1233.                 $this->inlinedRequires[$file] = true;
  1234.                 $code .= sprintf("\n            include_once %s;"$file);
  1235.             }
  1236.         }
  1237.         if ($hasProxyClasses) {
  1238.             $code .= "\n            include_once __DIR__.'/proxy-classes.php';";
  1239.         }
  1240.         return $code sprintf("\n        \$this->privates['service_container'] = function () {%s\n        };\n"$code) : '';
  1241.     }
  1242.     private function addDefaultParametersMethod(): string
  1243.     {
  1244.         if (!$this->container->getParameterBag()->all()) {
  1245.             return '';
  1246.         }
  1247.         $php = [];
  1248.         $dynamicPhp = [];
  1249.         foreach ($this->container->getParameterBag()->all() as $key => $value) {
  1250.             if ($key !== $resolvedKey $this->container->resolveEnvPlaceholders($key)) {
  1251.                 throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: "%s".'$resolvedKey));
  1252.             }
  1253.             $hasEnum false;
  1254.             $export $this->exportParameters([$value], ''12$hasEnum);
  1255.             $export explode('0 => 'substr(rtrim($export" ]\n"), 2, -1), 2);
  1256.             if ($hasEnum || preg_match("/\\\$this->(?:getEnv\('(?:[-.\w]*+:)*+\w++'\)|targetDir\.'')/"$export[1])) {
  1257.                 $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;'$export[0], $this->export($key), $export[1]);
  1258.             } else {
  1259.                 $php[] = sprintf('%s%s => %s,'$export[0], $this->export($key), $export[1]);
  1260.             }
  1261.         }
  1262.         $parameters sprintf("[\n%s\n%s]"implode("\n"$php), str_repeat(' '8));
  1263.         $code = <<<'EOF'
  1264.     /**
  1265.      * @return array|bool|float|int|string|\UnitEnum|null
  1266.      */
  1267.     public function getParameter(string $name)
  1268.     {
  1269.         if (isset($this->buildParameters[$name])) {
  1270.             return $this->buildParameters[$name];
  1271.         }
  1272.         if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters))) {
  1273.             throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
  1274.         }
  1275.         if (isset($this->loadedDynamicParameters[$name])) {
  1276.             return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
  1277.         }
  1278.         return $this->parameters[$name];
  1279.     }
  1280.     public function hasParameter(string $name): bool
  1281.     {
  1282.         if (isset($this->buildParameters[$name])) {
  1283.             return true;
  1284.         }
  1285.         return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters);
  1286.     }
  1287.     public function setParameter(string $name, $value): void
  1288.     {
  1289.         throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
  1290.     }
  1291.     public function getParameterBag(): ParameterBagInterface
  1292.     {
  1293.         if (null === $this->parameterBag) {
  1294.             $parameters = $this->parameters;
  1295.             foreach ($this->loadedDynamicParameters as $name => $loaded) {
  1296.                 $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
  1297.             }
  1298.             foreach ($this->buildParameters as $name => $value) {
  1299.                 $parameters[$name] = $value;
  1300.             }
  1301.             $this->parameterBag = new FrozenParameterBag($parameters);
  1302.         }
  1303.         return $this->parameterBag;
  1304.     }
  1305. EOF;
  1306.         if (!$this->asFiles) {
  1307.             $code preg_replace('/^.*buildParameters.*\n.*\n.*\n\n?/m'''$code);
  1308.         }
  1309.         if ($dynamicPhp) {
  1310.             $loadedDynamicParameters $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, \count($dynamicPhp), false)), ''8);
  1311.             $getDynamicParameter = <<<'EOF'
  1312.         switch ($name) {
  1313. %s
  1314.             default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name));
  1315.         }
  1316.         $this->loadedDynamicParameters[$name] = true;
  1317.         return $this->dynamicParameters[$name] = $value;
  1318. EOF;
  1319.             $getDynamicParameter sprintf($getDynamicParameterimplode("\n"$dynamicPhp));
  1320.         } else {
  1321.             $loadedDynamicParameters '[]';
  1322.             $getDynamicParameter str_repeat(' '8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));';
  1323.         }
  1324.         $code .= <<<EOF
  1325.     private \$loadedDynamicParameters = {$loadedDynamicParameters};
  1326.     private \$dynamicParameters = [];
  1327.     private function getDynamicParameter(string \$name)
  1328.     {
  1329. {$getDynamicParameter}
  1330.     }
  1331.     protected function getDefaultParameters(): array
  1332.     {
  1333.         return $parameters;
  1334.     }
  1335. EOF;
  1336.         return $code;
  1337.     }
  1338.     /**
  1339.      * @throws InvalidArgumentException
  1340.      */
  1341.     private function exportParameters(array $parametersstring $path ''int $indent 12bool &$hasEnum false): string
  1342.     {
  1343.         $php = [];
  1344.         foreach ($parameters as $key => $value) {
  1345.             if (\is_array($value)) {
  1346.                 $value $this->exportParameters($value$path.'/'.$key$indent 4$hasEnum);
  1347.             } elseif ($value instanceof ArgumentInterface) {
  1348.                 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain special arguments. "%s" found in "%s".'get_debug_type($value), $path.'/'.$key));
  1349.             } elseif ($value instanceof Variable) {
  1350.                 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".'$value$path.'/'.$key));
  1351.             } elseif ($value instanceof Definition) {
  1352.                 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".'$value->getClass(), $path.'/'.$key));
  1353.             } elseif ($value instanceof Reference) {
  1354.                 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").'$value$path.'/'.$key));
  1355.             } elseif ($value instanceof Expression) {
  1356.                 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".'$value$path.'/'.$key));
  1357.             } elseif ($value instanceof \UnitEnum) {
  1358.                 $hasEnum true;
  1359.                 $value sprintf('\%s::%s', \get_class($value), $value->name);
  1360.             } else {
  1361.                 $value $this->export($value);
  1362.             }
  1363.             $php[] = sprintf('%s%s => %s,'str_repeat(' '$indent), $this->export($key), $value);
  1364.         }
  1365.         return sprintf("[\n%s\n%s]"implode("\n"$php), str_repeat(' '$indent 4));
  1366.     }
  1367.     private function endClass(): string
  1368.     {
  1369.         if ($this->addThrow) {
  1370.             return <<<'EOF'
  1371.     protected function throw($message)
  1372.     {
  1373.         throw new RuntimeException($message);
  1374.     }
  1375. }
  1376. EOF;
  1377.         }
  1378.         return <<<'EOF'
  1379. }
  1380. EOF;
  1381.     }
  1382.     private function wrapServiceConditionals($valuestring $code): string
  1383.     {
  1384.         if (!$condition $this->getServiceConditionals($value)) {
  1385.             return $code;
  1386.         }
  1387.         // re-indent the wrapped code
  1388.         $code implode("\n"array_map(function ($line) { return $line '    '.$line $line; }, explode("\n"$code)));
  1389.         return sprintf("        if (%s) {\n%s        }\n"$condition$code);
  1390.     }
  1391.     private function getServiceConditionals($value): string
  1392.     {
  1393.         $conditions = [];
  1394.         foreach (ContainerBuilder::getInitializedConditionals($value) as $service) {
  1395.             if (!$this->container->hasDefinition($service)) {
  1396.                 return 'false';
  1397.             }
  1398.             $conditions[] = sprintf('isset($this->%s[%s])'$this->container->getDefinition($service)->isPublic() ? 'services' 'privates'$this->doExport($service));
  1399.         }
  1400.         foreach (ContainerBuilder::getServiceConditionals($value) as $service) {
  1401.             if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) {
  1402.                 continue;
  1403.             }
  1404.             $conditions[] = sprintf('$this->has(%s)'$this->doExport($service));
  1405.         }
  1406.         if (!$conditions) {
  1407.             return '';
  1408.         }
  1409.         return implode(' && '$conditions);
  1410.     }
  1411.     private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions null, array &$calls = [], bool $byConstructor null): \SplObjectStorage
  1412.     {
  1413.         if (null === $definitions) {
  1414.             $definitions = new \SplObjectStorage();
  1415.         }
  1416.         foreach ($arguments as $argument) {
  1417.             if (\is_array($argument)) {
  1418.                 $this->getDefinitionsFromArguments($argument$definitions$calls$byConstructor);
  1419.             } elseif ($argument instanceof Reference) {
  1420.                 $id = (string) $argument;
  1421.                 while ($this->container->hasAlias($id)) {
  1422.                     $id = (string) $this->container->getAlias($id);
  1423.                 }
  1424.                 if (!isset($calls[$id])) {
  1425.                     $calls[$id] = [0$argument->getInvalidBehavior(), $byConstructor];
  1426.                 } else {
  1427.                     $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior());
  1428.                 }
  1429.                 ++$calls[$id][0];
  1430.             } elseif (!$argument instanceof Definition) {
  1431.                 // no-op
  1432.             } elseif (isset($definitions[$argument])) {
  1433.                 $definitions[$argument] = $definitions[$argument];
  1434.             } else {
  1435.                 $definitions[$argument] = 1;
  1436.                 $arguments = [$argument->getArguments(), $argument->getFactory()];
  1437.                 $this->getDefinitionsFromArguments($arguments$definitions$callsnull === $byConstructor || $byConstructor);
  1438.                 $arguments = [$argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()];
  1439.                 $this->getDefinitionsFromArguments($arguments$definitions$callsnull !== $byConstructor && $byConstructor);
  1440.             }
  1441.         }
  1442.         return $definitions;
  1443.     }
  1444.     /**
  1445.      * @throws RuntimeException
  1446.      */
  1447.     private function dumpValue($valuebool $interpolate true): string
  1448.     {
  1449.         if (\is_array($value)) {
  1450.             if ($value && $interpolate && false !== $param array_search($value$this->container->getParameterBag()->all(), true)) {
  1451.                 return $this->dumpValue("%$param%");
  1452.             }
  1453.             $code = [];
  1454.             foreach ($value as $k => $v) {
  1455.                 $code[] = sprintf('%s => %s'$this->dumpValue($k$interpolate), $this->dumpValue($v$interpolate));
  1456.             }
  1457.             return sprintf('[%s]'implode(', '$code));
  1458.         } elseif ($value instanceof ArgumentInterface) {
  1459.             $scope = [$this->definitionVariables$this->referenceVariables];
  1460.             $this->definitionVariables $this->referenceVariables null;
  1461.             try {
  1462.                 if ($value instanceof ServiceClosureArgument) {
  1463.                     $value $value->getValues()[0];
  1464.                     $code $this->dumpValue($value$interpolate);
  1465.                     $returnedType '';
  1466.                     if ($value instanceof TypedReference) {
  1467.                         $returnedType sprintf(': %s\%s'ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $value->getInvalidBehavior() ? '' '?'str_replace(['|''&'], ['|\\''&\\'], $value->getType()));
  1468.                     }
  1469.                     $code sprintf('return %s;'$code);
  1470.                     return sprintf("function ()%s {\n            %s\n        }"$returnedType$code);
  1471.                 }
  1472.                 if ($value instanceof IteratorArgument) {
  1473.                     $operands = [0];
  1474.                     $code = [];
  1475.                     $code[] = 'new RewindableGenerator(function () {';
  1476.                     if (!$values $value->getValues()) {
  1477.                         $code[] = '            return new \EmptyIterator();';
  1478.                     } else {
  1479.                         $countCode = [];
  1480.                         $countCode[] = 'function () {';
  1481.                         foreach ($values as $k => $v) {
  1482.                             ($c $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0];
  1483.                             $v $this->wrapServiceConditionals($vsprintf("        yield %s => %s;\n"$this->dumpValue($k$interpolate), $this->dumpValue($v$interpolate)));
  1484.                             foreach (explode("\n"$v) as $v) {
  1485.                                 if ($v) {
  1486.                                     $code[] = '    '.$v;
  1487.                                 }
  1488.                             }
  1489.                         }
  1490.                         $countCode[] = sprintf('            return %s;'implode(' + '$operands));
  1491.                         $countCode[] = '        }';
  1492.                     }
  1493.                     $code[] = sprintf('        }, %s)', \count($operands) > implode("\n"$countCode) : $operands[0]);
  1494.                     return implode("\n"$code);
  1495.                 }
  1496.                 if ($value instanceof ServiceLocatorArgument) {
  1497.                     $serviceMap '';
  1498.                     $serviceTypes '';
  1499.                     foreach ($value->getValues() as $k => $v) {
  1500.                         if (!$v) {
  1501.                             continue;
  1502.                         }
  1503.                         $id = (string) $v;
  1504.                         while ($this->container->hasAlias($id)) {
  1505.                             $id = (string) $this->container->getAlias($id);
  1506.                         }
  1507.                         $definition $this->container->getDefinition($id);
  1508.                         $load = !($definition->hasErrors() && $e $definition->getErrors()) ? $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition) : reset($e);
  1509.                         $serviceMap .= sprintf("\n            %s => [%s, %s, %s, %s],",
  1510.                             $this->export($k),
  1511.                             $this->export($definition->isShared() ? ($definition->isPublic() ? 'services' 'privates') : false),
  1512.                             $this->doExport($id),
  1513.                             $this->export(ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $v->getInvalidBehavior() && !\is_string($load) ? $this->generateMethodName($id) : null),
  1514.                             $this->export($load)
  1515.                         );
  1516.                         $serviceTypes .= sprintf("\n            %s => %s,"$this->export($k), $this->export($v instanceof TypedReference $v->getType() : '?'));
  1517.                         $this->locatedIds[$id] = true;
  1518.                     }
  1519.                     $this->addGetService true;
  1520.                     return sprintf('new \%s($this->getService, [%s%s], [%s%s])'ServiceLocator::class, $serviceMap$serviceMap "\n        " ''$serviceTypes$serviceTypes "\n        " '');
  1521.                 }
  1522.             } finally {
  1523.                 [$this->definitionVariables$this->referenceVariables] = $scope;
  1524.             }
  1525.         } elseif ($value instanceof Definition) {
  1526.             if ($value->hasErrors() && $e $value->getErrors()) {
  1527.                 $this->addThrow true;
  1528.                 return sprintf('$this->throw(%s)'$this->export(reset($e)));
  1529.             }
  1530.             if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
  1531.                 return $this->dumpValue($this->definitionVariables[$value], $interpolate);
  1532.             }
  1533.             if ($value->getMethodCalls()) {
  1534.                 throw new RuntimeException('Cannot dump definitions which have method calls.');
  1535.             }
  1536.             if ($value->getProperties()) {
  1537.                 throw new RuntimeException('Cannot dump definitions which have properties.');
  1538.             }
  1539.             if (null !== $value->getConfigurator()) {
  1540.                 throw new RuntimeException('Cannot dump definitions which have a configurator.');
  1541.             }
  1542.             return $this->addNewInstance($value);
  1543.         } elseif ($value instanceof Variable) {
  1544.             return '$'.$value;
  1545.         } elseif ($value instanceof Reference) {
  1546.             $id = (string) $value;
  1547.             while ($this->container->hasAlias($id)) {
  1548.                 $id = (string) $this->container->getAlias($id);
  1549.             }
  1550.             if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) {
  1551.                 return $this->dumpValue($this->referenceVariables[$id], $interpolate);
  1552.             }
  1553.             return $this->getServiceCall($id$value);
  1554.         } elseif ($value instanceof Expression) {
  1555.             return $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']);
  1556.         } elseif ($value instanceof Parameter) {
  1557.             return $this->dumpParameter($value);
  1558.         } elseif (true === $interpolate && \is_string($value)) {
  1559.             if (preg_match('/^%([^%]+)%$/'$value$match)) {
  1560.                 // we do this to deal with non string values (Boolean, integer, ...)
  1561.                 // the preg_replace_callback converts them to strings
  1562.                 return $this->dumpParameter($match[1]);
  1563.             } else {
  1564.                 $replaceParameters = function ($match) {
  1565.                     return "'.".$this->dumpParameter($match[2]).".'";
  1566.                 };
  1567.                 $code str_replace('%%''%'preg_replace_callback('/(?<!%)(%)([^%]+)\1/'$replaceParameters$this->export($value)));
  1568.                 return $code;
  1569.             }
  1570.         } elseif ($value instanceof \UnitEnum) {
  1571.             return sprintf('\%s::%s', \get_class($value), $value->name);
  1572.         } elseif ($value instanceof AbstractArgument) {
  1573.             throw new RuntimeException($value->getTextWithContext());
  1574.         } elseif (\is_object($value) || \is_resource($value)) {
  1575.             throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
  1576.         }
  1577.         return $this->export($value);
  1578.     }
  1579.     /**
  1580.      * Dumps a string to a literal (aka PHP Code) class value.
  1581.      *
  1582.      * @throws RuntimeException
  1583.      */
  1584.     private function dumpLiteralClass(string $class): string
  1585.     {
  1586.         if (str_contains($class'$')) {
  1587.             return sprintf('${($_ = %s) && false ?: "_"}'$class);
  1588.         }
  1589.         if (!str_starts_with($class"'") || !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/'$class)) {
  1590.             throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s).'$class ?: 'n/a'));
  1591.         }
  1592.         $class substr(str_replace('\\\\''\\'$class), 1, -1);
  1593.         return str_starts_with($class'\\') ? $class '\\'.$class;
  1594.     }
  1595.     private function dumpParameter(string $name): string
  1596.     {
  1597.         if ($this->container->hasParameter($name)) {
  1598.             $value $this->container->getParameter($name);
  1599.             $dumpedValue $this->dumpValue($valuefalse);
  1600.             if (!$value || !\is_array($value)) {
  1601.                 return $dumpedValue;
  1602.             }
  1603.             if (!preg_match("/\\\$this->(?:getEnv\('(?:[-.\w]*+:)*+\w++'\)|targetDir\.'')/"$dumpedValue)) {
  1604.                 return sprintf('$this->parameters[%s]'$this->doExport($name));
  1605.             }
  1606.         }
  1607.         return sprintf('$this->getParameter(%s)'$this->doExport($name));
  1608.     }
  1609.     private function getServiceCall(string $idReference $reference null): string
  1610.     {
  1611.         while ($this->container->hasAlias($id)) {
  1612.             $id = (string) $this->container->getAlias($id);
  1613.         }
  1614.         if ('service_container' === $id) {
  1615.             return '$this';
  1616.         }
  1617.         if ($this->container->hasDefinition($id) && $definition $this->container->getDefinition($id)) {
  1618.             if ($definition->isSynthetic()) {
  1619.                 $code sprintf('$this->get(%s%s)'$this->doExport($id), null !== $reference ', '.$reference->getInvalidBehavior() : '');
  1620.             } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
  1621.                 $code 'null';
  1622.                 if (!$definition->isShared()) {
  1623.                     return $code;
  1624.                 }
  1625.             } elseif ($this->isTrivialInstance($definition)) {
  1626.                 if ($definition->hasErrors() && $e $definition->getErrors()) {
  1627.                     $this->addThrow true;
  1628.                     return sprintf('$this->throw(%s)'$this->export(reset($e)));
  1629.                 }
  1630.                 $code $this->addNewInstance($definition''$id);
  1631.                 if ($definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
  1632.                     $code sprintf('$this->%s[%s] = %s'$definition->isPublic() ? 'services' 'privates'$this->doExport($id), $code);
  1633.                 }
  1634.                 $code "($code)";
  1635.             } else {
  1636.                 $code $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition) ? "\$this->load('%s')" '$this->%s()';
  1637.                 $code sprintf($code$this->generateMethodName($id));
  1638.                 if (!$definition->isShared()) {
  1639.                     $factory sprintf('$this->factories%s[%s]'$definition->isPublic() ? '' "['service_container']"$this->doExport($id));
  1640.                     $code sprintf('(isset(%s) ? %1$s() : %s)'$factory$code);
  1641.                 }
  1642.             }
  1643.             if ($definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
  1644.                 $code sprintf('($this->%s[%s] ?? %s)'$definition->isPublic() ? 'services' 'privates'$this->doExport($id), $code);
  1645.             }
  1646.             return $code;
  1647.         }
  1648.         if (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
  1649.             return 'null';
  1650.         }
  1651.         if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE $reference->getInvalidBehavior()) {
  1652.             $code sprintf('$this->get(%s, /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)'$this->doExport($id), ContainerInterface::NULL_ON_INVALID_REFERENCE);
  1653.         } else {
  1654.             $code sprintf('$this->get(%s)'$this->doExport($id));
  1655.         }
  1656.         return sprintf('($this->services[%s] ?? %s)'$this->doExport($id), $code);
  1657.     }
  1658.     /**
  1659.      * Initializes the method names map to avoid conflicts with the Container methods.
  1660.      */
  1661.     private function initializeMethodNamesMap(string $class)
  1662.     {
  1663.         $this->serviceIdToMethodNameMap = [];
  1664.         $this->usedMethodNames = [];
  1665.         if ($reflectionClass $this->container->getReflectionClass($class)) {
  1666.             foreach ($reflectionClass->getMethods() as $method) {
  1667.                 $this->usedMethodNames[strtolower($method->getName())] = true;
  1668.             }
  1669.         }
  1670.     }
  1671.     /**
  1672.      * @throws InvalidArgumentException
  1673.      */
  1674.     private function generateMethodName(string $id): string
  1675.     {
  1676.         if (isset($this->serviceIdToMethodNameMap[$id])) {
  1677.             return $this->serviceIdToMethodNameMap[$id];
  1678.         }
  1679.         $i strrpos($id'\\');
  1680.         $name Container::camelize(false !== $i && isset($id[$i]) ? substr($id$i) : $id);
  1681.         $name preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/'''$name);
  1682.         $methodName 'get'.$name.'Service';
  1683.         $suffix 1;
  1684.         while (isset($this->usedMethodNames[strtolower($methodName)])) {
  1685.             ++$suffix;
  1686.             $methodName 'get'.$name.$suffix.'Service';
  1687.         }
  1688.         $this->serviceIdToMethodNameMap[$id] = $methodName;
  1689.         $this->usedMethodNames[strtolower($methodName)] = true;
  1690.         return $methodName;
  1691.     }
  1692.     private function getNextVariableName(): string
  1693.     {
  1694.         $firstChars self::FIRST_CHARS;
  1695.         $firstCharsLength = \strlen($firstChars);
  1696.         $nonFirstChars self::NON_FIRST_CHARS;
  1697.         $nonFirstCharsLength = \strlen($nonFirstChars);
  1698.         while (true) {
  1699.             $name '';
  1700.             $i $this->variableCount;
  1701.             if ('' === $name) {
  1702.                 $name .= $firstChars[$i $firstCharsLength];
  1703.                 $i = (int) ($i $firstCharsLength);
  1704.             }
  1705.             while ($i 0) {
  1706.                 --$i;
  1707.                 $name .= $nonFirstChars[$i $nonFirstCharsLength];
  1708.                 $i = (int) ($i $nonFirstCharsLength);
  1709.             }
  1710.             ++$this->variableCount;
  1711.             // check that the name is not reserved
  1712.             if (\in_array($name$this->reservedVariablestrue)) {
  1713.                 continue;
  1714.             }
  1715.             return $name;
  1716.         }
  1717.     }
  1718.     private function getExpressionLanguage(): ExpressionLanguage
  1719.     {
  1720.         if (null === $this->expressionLanguage) {
  1721.             if (!class_exists(\Symfony\Component\ExpressionLanguage\ExpressionLanguage::class)) {
  1722.                 throw new LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  1723.             }
  1724.             $providers $this->container->getExpressionLanguageProviders();
  1725.             $this->expressionLanguage = new ExpressionLanguage(null$providers, function ($arg) {
  1726.                 $id '""' === substr_replace($arg''1, -1) ? stripcslashes(substr($arg1, -1)) : null;
  1727.                 if (null !== $id && ($this->container->hasAlias($id) || $this->container->hasDefinition($id))) {
  1728.                     return $this->getServiceCall($id);
  1729.                 }
  1730.                 return sprintf('$this->get(%s)'$arg);
  1731.             });
  1732.             if ($this->container->isTrackingResources()) {
  1733.                 foreach ($providers as $provider) {
  1734.                     $this->container->addObjectResource($provider);
  1735.                 }
  1736.             }
  1737.         }
  1738.         return $this->expressionLanguage;
  1739.     }
  1740.     private function isHotPath(Definition $definition): bool
  1741.     {
  1742.         return $this->hotPathTag && $definition->hasTag($this->hotPathTag) && !$definition->isDeprecated();
  1743.     }
  1744.     private function isSingleUsePrivateNode(ServiceReferenceGraphNode $node): bool
  1745.     {
  1746.         if ($node->getValue()->isPublic()) {
  1747.             return false;
  1748.         }
  1749.         $ids = [];
  1750.         foreach ($node->getInEdges() as $edge) {
  1751.             if (!$value $edge->getSourceNode()->getValue()) {
  1752.                 continue;
  1753.             }
  1754.             if ($edge->isLazy() || !$value instanceof Definition || !$value->isShared()) {
  1755.                 return false;
  1756.             }
  1757.             $ids[$edge->getSourceNode()->getId()] = true;
  1758.         }
  1759.         return === \count($ids);
  1760.     }
  1761.     /**
  1762.      * @return mixed
  1763.      */
  1764.     private function export($value)
  1765.     {
  1766.         if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex$value$matches, \PREG_OFFSET_CAPTURE)) {
  1767.             $suffix $matches[0][1] + \strlen($matches[0][0]);
  1768.             $matches[0][1] += \strlen($matches[1][0]);
  1769.             $prefix $matches[0][1] ? $this->doExport(substr($value0$matches[0][1]), true).'.' '';
  1770.             if ('\\' === \DIRECTORY_SEPARATOR && isset($value[$suffix])) {
  1771.                 $cookie '\\'.random_int(100000, \PHP_INT_MAX);
  1772.                 $suffix '.'.$this->doExport(str_replace('\\'$cookiesubstr($value$suffix)), true);
  1773.                 $suffix str_replace('\\'.$cookie"'.\\DIRECTORY_SEPARATOR.'"$suffix);
  1774.             } else {
  1775.                 $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value$suffix), true) : '';
  1776.             }
  1777.             $dirname $this->asFiles '$this->containerDir' '__DIR__';
  1778.             $offset $this->targetDirMaxMatches - \count($matches);
  1779.             if ($offset) {
  1780.                 $dirname sprintf('\dirname(__DIR__, %d)'$offset + (int) $this->asFiles);
  1781.             } elseif ($this->asFiles) {
  1782.                 $dirname "\$this->targetDir.''"// empty string concatenation on purpose
  1783.             }
  1784.             if ($prefix || $suffix) {
  1785.                 return sprintf('(%s%s%s)'$prefix$dirname$suffix);
  1786.             }
  1787.             return $dirname;
  1788.         }
  1789.         return $this->doExport($valuetrue);
  1790.     }
  1791.     /**
  1792.      * @return mixed
  1793.      */
  1794.     private function doExport($valuebool $resolveEnv false)
  1795.     {
  1796.         $shouldCacheValue $resolveEnv && \is_string($value);
  1797.         if ($shouldCacheValue && isset($this->exportedVariables[$value])) {
  1798.             return $this->exportedVariables[$value];
  1799.         }
  1800.         if (\is_string($value) && str_contains($value"\n")) {
  1801.             $cleanParts explode("\n"$value);
  1802.             $cleanParts array_map(function ($part) { return var_export($parttrue); }, $cleanParts);
  1803.             $export implode('."\n".'$cleanParts);
  1804.         } else {
  1805.             $export var_export($valuetrue);
  1806.         }
  1807.         if ($this->asFiles) {
  1808.             if (false !== strpos($export'$this')) {
  1809.                 $export str_replace('$this'"$'.'this"$export);
  1810.             }
  1811.             if (false !== strpos($export'function () {')) {
  1812.                 $export str_replace('function () {'"function ('.') {"$export);
  1813.             }
  1814.         }
  1815.         if ($resolveEnv && "'" === $export[0] && $export !== $resolvedExport $this->container->resolveEnvPlaceholders($export"'.\$this->getEnv('string:%s').'")) {
  1816.             $export $resolvedExport;
  1817.             if (str_ends_with($export".''")) {
  1818.                 $export substr($export0, -3);
  1819.                 if ("'" === $export[1]) {
  1820.                     $export substr_replace($export''187);
  1821.                 }
  1822.             }
  1823.             if ("'" === $export[1]) {
  1824.                 $export substr($export3);
  1825.             }
  1826.         }
  1827.         if ($shouldCacheValue) {
  1828.             $this->exportedVariables[$value] = $export;
  1829.         }
  1830.         return $export;
  1831.     }
  1832.     private function getAutoloadFile(): ?string
  1833.     {
  1834.         $file null;
  1835.         foreach (spl_autoload_functions() as $autoloader) {
  1836.             if (!\is_array($autoloader)) {
  1837.                 continue;
  1838.             }
  1839.             if ($autoloader[0] instanceof DebugClassLoader || $autoloader[0] instanceof LegacyDebugClassLoader) {
  1840.                 $autoloader $autoloader[0]->getClassLoader();
  1841.             }
  1842.             if (!\is_array($autoloader) || !$autoloader[0] instanceof ClassLoader || !$autoloader[0]->findFile(__CLASS__)) {
  1843.                 continue;
  1844.             }
  1845.             foreach (get_declared_classes() as $class) {
  1846.                 if (str_starts_with($class'ComposerAutoloaderInit') && $class::getLoader() === $autoloader[0]) {
  1847.                     $file = \dirname((new \ReflectionClass($class))->getFileName(), 2).'/autoload.php';
  1848.                     if (null !== $this->targetDirRegex && preg_match($this->targetDirRegex.'A'$file)) {
  1849.                         return $file;
  1850.                     }
  1851.                 }
  1852.             }
  1853.         }
  1854.         return $file;
  1855.     }
  1856.     private function getClasses(Definition $definitionstring $id): array
  1857.     {
  1858.         $classes = [];
  1859.         while ($definition instanceof Definition) {
  1860.             foreach ($definition->getTag($this->preloadTags[0]) as $tag) {
  1861.                 if (!isset($tag['class'])) {
  1862.                     throw new InvalidArgumentException(sprintf('Missing attribute "class" on tag "%s" for service "%s".'$this->preloadTags[0], $id));
  1863.                 }
  1864.                 $classes[] = trim($tag['class'], '\\');
  1865.             }
  1866.             if ($class $definition->getClass()) {
  1867.                 $classes[] = trim($class'\\');
  1868.             }
  1869.             $factory $definition->getFactory();
  1870.             if (!\is_array($factory)) {
  1871.                 $factory = [$factory];
  1872.             }
  1873.             if (\is_string($factory[0])) {
  1874.                 if (false !== $i strrpos($factory[0], '::')) {
  1875.                     $factory[0] = substr($factory[0], 0$i);
  1876.                 }
  1877.                 $classes[] = trim($factory[0], '\\');
  1878.             }
  1879.             $definition $factory[0];
  1880.         }
  1881.         return $classes;
  1882.     }
  1883. }