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

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