vendor/symfony/http-kernel/Kernel.php line 202

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\HttpKernel;
  11. use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator;
  12. use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
  13. use Symfony\Component\Config\Builder\ConfigBuilderGenerator;
  14. use Symfony\Component\Config\ConfigCache;
  15. use Symfony\Component\Config\Loader\DelegatingLoader;
  16. use Symfony\Component\Config\Loader\LoaderResolver;
  17. use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
  18. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  19. use Symfony\Component\DependencyInjection\Compiler\PassConfig;
  20. use Symfony\Component\DependencyInjection\ContainerBuilder;
  21. use Symfony\Component\DependencyInjection\ContainerInterface;
  22. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  23. use Symfony\Component\DependencyInjection\Dumper\Preloader;
  24. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  25. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  26. use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
  27. use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
  28. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  29. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  30. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  31. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  32. use Symfony\Component\ErrorHandler\DebugClassLoader;
  33. use Symfony\Component\Filesystem\Filesystem;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\HttpFoundation\Response;
  36. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  37. use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
  38. use Symfony\Component\HttpKernel\Config\FileLocator;
  39. use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
  40. use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
  41. // Help opcache.preload discover always-needed symbols
  42. class_exists(ConfigCache::class);
  43. /**
  44.  * The Kernel is the heart of the Symfony system.
  45.  *
  46.  * It manages an environment made of bundles.
  47.  *
  48.  * Environment names must always start with a letter and
  49.  * they must only contain letters and numbers.
  50.  *
  51.  * @author Fabien Potencier <fabien@symfony.com>
  52.  */
  53. abstract class Kernel implements KernelInterfaceRebootableInterfaceTerminableInterface
  54. {
  55.     /**
  56.      * @var array<string, BundleInterface>
  57.      */
  58.     protected $bundles = [];
  59.     protected $container;
  60.     protected $environment;
  61.     protected $debug;
  62.     protected $booted false;
  63.     protected $startTime;
  64.     private string $projectDir;
  65.     private ?string $warmupDir null;
  66.     private int $requestStackSize 0;
  67.     private bool $resetServices false;
  68.     /**
  69.      * @var array<string, bool>
  70.      */
  71.     private static array $freshCache = [];
  72.     public const VERSION '6.0.6';
  73.     public const VERSION_ID 60006;
  74.     public const MAJOR_VERSION 6;
  75.     public const MINOR_VERSION 0;
  76.     public const RELEASE_VERSION 6;
  77.     public const EXTRA_VERSION '';
  78.     public const END_OF_MAINTENANCE '01/2023';
  79.     public const END_OF_LIFE '01/2023';
  80.     public function __construct(string $environmentbool $debug)
  81.     {
  82.         if (!$this->environment $environment) {
  83.             throw new \InvalidArgumentException(sprintf('Invalid environment provided to "%s": the environment cannot be empty.'get_debug_type($this)));
  84.         }
  85.         $this->debug $debug;
  86.     }
  87.     public function __clone()
  88.     {
  89.         $this->booted false;
  90.         $this->container null;
  91.         $this->requestStackSize 0;
  92.         $this->resetServices false;
  93.     }
  94.     /**
  95.      * {@inheritdoc}
  96.      */
  97.     public function boot()
  98.     {
  99.         if (true === $this->booted) {
  100.             if (!$this->requestStackSize && $this->resetServices) {
  101.                 if ($this->container->has('services_resetter')) {
  102.                     $this->container->get('services_resetter')->reset();
  103.                 }
  104.                 $this->resetServices false;
  105.                 if ($this->debug) {
  106.                     $this->startTime microtime(true);
  107.                 }
  108.             }
  109.             return;
  110.         }
  111.         if (null === $this->container) {
  112.             $this->preBoot();
  113.         }
  114.         foreach ($this->getBundles() as $bundle) {
  115.             $bundle->setContainer($this->container);
  116.             $bundle->boot();
  117.         }
  118.         $this->booted true;
  119.     }
  120.     /**
  121.      * {@inheritdoc}
  122.      */
  123.     public function reboot(?string $warmupDir)
  124.     {
  125.         $this->shutdown();
  126.         $this->warmupDir $warmupDir;
  127.         $this->boot();
  128.     }
  129.     /**
  130.      * {@inheritdoc}
  131.      */
  132.     public function terminate(Request $requestResponse $response)
  133.     {
  134.         if (false === $this->booted) {
  135.             return;
  136.         }
  137.         if ($this->getHttpKernel() instanceof TerminableInterface) {
  138.             $this->getHttpKernel()->terminate($request$response);
  139.         }
  140.     }
  141.     /**
  142.      * {@inheritdoc}
  143.      */
  144.     public function shutdown()
  145.     {
  146.         if (false === $this->booted) {
  147.             return;
  148.         }
  149.         $this->booted false;
  150.         foreach ($this->getBundles() as $bundle) {
  151.             $bundle->shutdown();
  152.             $bundle->setContainer(null);
  153.         }
  154.         $this->container null;
  155.         $this->requestStackSize 0;
  156.         $this->resetServices false;
  157.     }
  158.     /**
  159.      * {@inheritdoc}
  160.      */
  161.     public function handle(Request $requestint $type HttpKernelInterface::MAIN_REQUESTbool $catch true): Response
  162.     {
  163.         if (!$this->booted) {
  164.             $container $this->container ?? $this->preBoot();
  165.             if ($container->has('http_cache')) {
  166.                 return $container->get('http_cache')->handle($request$type$catch);
  167.             }
  168.         }
  169.         $this->boot();
  170.         ++$this->requestStackSize;
  171.         $this->resetServices true;
  172.         try {
  173.             return $this->getHttpKernel()->handle($request$type$catch);
  174.         } finally {
  175.             --$this->requestStackSize;
  176.         }
  177.     }
  178.     /**
  179.      * Gets an HTTP kernel from the container.
  180.      */
  181.     protected function getHttpKernel(): HttpKernelInterface
  182.     {
  183.         return $this->container->get('http_kernel');
  184.     }
  185.     /**
  186.      * {@inheritdoc}
  187.      */
  188.     public function getBundles(): array
  189.     {
  190.         return $this->bundles;
  191.     }
  192.     /**
  193.      * {@inheritdoc}
  194.      */
  195.     public function getBundle(string $name): BundleInterface
  196.     {
  197.         if (!isset($this->bundles[$name])) {
  198.             throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled. Maybe you forgot to add it in the "registerBundles()" method of your "%s.php" file?'$nameget_debug_type($this)));
  199.         }
  200.         return $this->bundles[$name];
  201.     }
  202.     /**
  203.      * {@inheritdoc}
  204.      */
  205.     public function locateResource(string $name): string
  206.     {
  207.         if ('@' !== $name[0]) {
  208.             throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).'$name));
  209.         }
  210.         if (str_contains($name'..')) {
  211.             throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).'$name));
  212.         }
  213.         $bundleName substr($name1);
  214.         $path '';
  215.         if (str_contains($bundleName'/')) {
  216.             [$bundleName$path] = explode('/'$bundleName2);
  217.         }
  218.         $bundle $this->getBundle($bundleName);
  219.         if (file_exists($file $bundle->getPath().'/'.$path)) {
  220.             return $file;
  221.         }
  222.         throw new \InvalidArgumentException(sprintf('Unable to find file "%s".'$name));
  223.     }
  224.     /**
  225.      * {@inheritdoc}
  226.      */
  227.     public function getEnvironment(): string
  228.     {
  229.         return $this->environment;
  230.     }
  231.     /**
  232.      * {@inheritdoc}
  233.      */
  234.     public function isDebug(): bool
  235.     {
  236.         return $this->debug;
  237.     }
  238.     /**
  239.      * Gets the application root dir (path of the project's composer file).
  240.      */
  241.     public function getProjectDir(): string
  242.     {
  243.         if (!isset($this->projectDir)) {
  244.             $r = new \ReflectionObject($this);
  245.             if (!is_file($dir $r->getFileName())) {
  246.                 throw new \LogicException(sprintf('Cannot auto-detect project dir for kernel of class "%s".'$r->name));
  247.             }
  248.             $dir $rootDir \dirname($dir);
  249.             while (!is_file($dir.'/composer.json')) {
  250.                 if ($dir === \dirname($dir)) {
  251.                     return $this->projectDir $rootDir;
  252.                 }
  253.                 $dir \dirname($dir);
  254.             }
  255.             $this->projectDir $dir;
  256.         }
  257.         return $this->projectDir;
  258.     }
  259.     /**
  260.      * {@inheritdoc}
  261.      */
  262.     public function getContainer(): ContainerInterface
  263.     {
  264.         if (!$this->container) {
  265.             throw new \LogicException('Cannot retrieve the container from a non-booted kernel.');
  266.         }
  267.         return $this->container;
  268.     }
  269.     /**
  270.      * @internal
  271.      */
  272.     public function setAnnotatedClassCache(array $annotatedClasses)
  273.     {
  274.         file_put_contents(($this->warmupDir ?: $this->getBuildDir()).'/annotations.map'sprintf('<?php return %s;'var_export($annotatedClassestrue)));
  275.     }
  276.     /**
  277.      * {@inheritdoc}
  278.      */
  279.     public function getStartTime(): float
  280.     {
  281.         return $this->debug && null !== $this->startTime $this->startTime : -\INF;
  282.     }
  283.     /**
  284.      * {@inheritdoc}
  285.      */
  286.     public function getCacheDir(): string
  287.     {
  288.         return $this->getProjectDir().'/var/cache/'.$this->environment;
  289.     }
  290.     /**
  291.      * {@inheritdoc}
  292.      */
  293.     public function getBuildDir(): string
  294.     {
  295.         // Returns $this->getCacheDir() for backward compatibility
  296.         return $this->getCacheDir();
  297.     }
  298.     /**
  299.      * {@inheritdoc}
  300.      */
  301.     public function getLogDir(): string
  302.     {
  303.         return $this->getProjectDir().'/var/log';
  304.     }
  305.     /**
  306.      * {@inheritdoc}
  307.      */
  308.     public function getCharset(): string
  309.     {
  310.         return 'UTF-8';
  311.     }
  312.     /**
  313.      * Gets the patterns defining the classes to parse and cache for annotations.
  314.      */
  315.     public function getAnnotatedClassesToCompile(): array
  316.     {
  317.         return [];
  318.     }
  319.     /**
  320.      * Initializes bundles.
  321.      *
  322.      * @throws \LogicException if two bundles share a common name
  323.      */
  324.     protected function initializeBundles()
  325.     {
  326.         // init bundles
  327.         $this->bundles = [];
  328.         foreach ($this->registerBundles() as $bundle) {
  329.             $name $bundle->getName();
  330.             if (isset($this->bundles[$name])) {
  331.                 throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s".'$name));
  332.             }
  333.             $this->bundles[$name] = $bundle;
  334.         }
  335.     }
  336.     /**
  337.      * The extension point similar to the Bundle::build() method.
  338.      *
  339.      * Use this method to register compiler passes and manipulate the container during the building process.
  340.      */
  341.     protected function build(ContainerBuilder $container)
  342.     {
  343.     }
  344.     /**
  345.      * Gets the container class.
  346.      *
  347.      * @throws \InvalidArgumentException If the generated classname is invalid
  348.      */
  349.     protected function getContainerClass(): string
  350.     {
  351.         $class = static::class;
  352.         $class str_contains($class"@anonymous\0") ? get_parent_class($class).str_replace('.''_'ContainerBuilder::hash($class)) : $class;
  353.         $class str_replace('\\''_'$class).ucfirst($this->environment).($this->debug 'Debug' '').'Container';
  354.         if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/'$class)) {
  355.             throw new \InvalidArgumentException(sprintf('The environment "%s" contains invalid characters, it can only contain characters allowed in PHP class names.'$this->environment));
  356.         }
  357.         return $class;
  358.     }
  359.     /**
  360.      * Gets the container's base class.
  361.      *
  362.      * All names except Container must be fully qualified.
  363.      */
  364.     protected function getContainerBaseClass(): string
  365.     {
  366.         return 'Container';
  367.     }
  368.     /**
  369.      * Initializes the service container.
  370.      *
  371.      * The built version of the service container is used when fresh, otherwise the
  372.      * container is built.
  373.      */
  374.     protected function initializeContainer()
  375.     {
  376.         $class $this->getContainerClass();
  377.         $buildDir $this->warmupDir ?: $this->getBuildDir();
  378.         $cache = new ConfigCache($buildDir.'/'.$class.'.php'$this->debug);
  379.         $cachePath $cache->getPath();
  380.         // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
  381.         $errorLevel error_reporting(\E_ALL \E_WARNING);
  382.         try {
  383.             if (is_file($cachePath) && \is_object($this->container = include $cachePath)
  384.                 && (!$this->debug || (self::$freshCache[$cachePath] ?? $cache->isFresh()))
  385.             ) {
  386.                 self::$freshCache[$cachePath] = true;
  387.                 $this->container->set('kernel'$this);
  388.                 error_reporting($errorLevel);
  389.                 return;
  390.             }
  391.         } catch (\Throwable $e) {
  392.         }
  393.         $oldContainer \is_object($this->container) ? new \ReflectionClass($this->container) : $this->container null;
  394.         try {
  395.             is_dir($buildDir) ?: mkdir($buildDir0777true);
  396.             if ($lock fopen($cachePath.'.lock''w')) {
  397.                 flock($lock\LOCK_EX \LOCK_NB$wouldBlock);
  398.                 if (!flock($lock$wouldBlock \LOCK_SH \LOCK_EX)) {
  399.                     fclose($lock);
  400.                     $lock null;
  401.                 } elseif (!is_file($cachePath) || !\is_object($this->container = include $cachePath)) {
  402.                     $this->container null;
  403.                 } elseif (!$oldContainer || \get_class($this->container) !== $oldContainer->name) {
  404.                     flock($lock\LOCK_UN);
  405.                     fclose($lock);
  406.                     $this->container->set('kernel'$this);
  407.                     return;
  408.                 }
  409.             }
  410.         } catch (\Throwable $e) {
  411.         } finally {
  412.             error_reporting($errorLevel);
  413.         }
  414.         if ($collectDeprecations $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) {
  415.             $collectedLogs = [];
  416.             $previousHandler set_error_handler(function ($type$message$file$line) use (&$collectedLogs, &$previousHandler) {
  417.                 if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) {
  418.                     return $previousHandler $previousHandler($type$message$file$line) : false;
  419.                 }
  420.                 if (isset($collectedLogs[$message])) {
  421.                     ++$collectedLogs[$message]['count'];
  422.                     return null;
  423.                 }
  424.                 $backtrace debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS5);
  425.                 // Clean the trace by removing first frames added by the error handler itself.
  426.                 for ($i 0; isset($backtrace[$i]); ++$i) {
  427.                     if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  428.                         $backtrace \array_slice($backtrace$i);
  429.                         break;
  430.                     }
  431.                 }
  432.                 for ($i 0; isset($backtrace[$i]); ++$i) {
  433.                     if (!isset($backtrace[$i]['file'], $backtrace[$i]['line'], $backtrace[$i]['function'])) {
  434.                         continue;
  435.                     }
  436.                     if (!isset($backtrace[$i]['class']) && 'trigger_deprecation' === $backtrace[$i]['function']) {
  437.                         $file $backtrace[$i]['file'];
  438.                         $line $backtrace[$i]['line'];
  439.                         $backtrace \array_slice($backtrace$i);
  440.                         break;
  441.                     }
  442.                 }
  443.                 // Remove frames added by DebugClassLoader.
  444.                 for ($i \count($backtrace) - 2$i; --$i) {
  445.                     if (\in_array($backtrace[$i]['class'] ?? null, [DebugClassLoader::class, LegacyDebugClassLoader::class], true)) {
  446.                         $backtrace = [$backtrace[$i 1]];
  447.                         break;
  448.                     }
  449.                 }
  450.                 $collectedLogs[$message] = [
  451.                     'type' => $type,
  452.                     'message' => $message,
  453.                     'file' => $file,
  454.                     'line' => $line,
  455.                     'trace' => [$backtrace[0]],
  456.                     'count' => 1,
  457.                 ];
  458.                 return null;
  459.             });
  460.         }
  461.         try {
  462.             $container null;
  463.             $container $this->buildContainer();
  464.             $container->compile();
  465.         } finally {
  466.             if ($collectDeprecations) {
  467.                 restore_error_handler();
  468.                 @file_put_contents($buildDir.'/'.$class.'Deprecations.log'serialize(array_values($collectedLogs)));
  469.                 @file_put_contents($buildDir.'/'.$class.'Compiler.log'null !== $container implode("\n"$container->getCompiler()->getLog()) : '');
  470.             }
  471.         }
  472.         $this->dumpContainer($cache$container$class$this->getContainerBaseClass());
  473.         if ($lock) {
  474.             flock($lock\LOCK_UN);
  475.             fclose($lock);
  476.         }
  477.         $this->container = require $cachePath;
  478.         $this->container->set('kernel'$this);
  479.         if ($oldContainer && \get_class($this->container) !== $oldContainer->name) {
  480.             // Because concurrent requests might still be using them,
  481.             // old container files are not removed immediately,
  482.             // but on a next dump of the container.
  483.             static $legacyContainers = [];
  484.             $oldContainerDir \dirname($oldContainer->getFileName());
  485.             $legacyContainers[$oldContainerDir.'.legacy'] = true;
  486.             foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy'\GLOB_NOSORT) as $legacyContainer) {
  487.                 if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
  488.                     (new Filesystem())->remove(substr($legacyContainer0, -7));
  489.                 }
  490.             }
  491.             touch($oldContainerDir.'.legacy');
  492.         }
  493.         $preload $this instanceof WarmableInterface ? (array) $this->warmUp($this->container->getParameter('kernel.cache_dir')) : [];
  494.         if ($this->container->has('cache_warmer')) {
  495.             $preload array_merge($preload, (array) $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir')));
  496.         }
  497.         if ($preload && method_exists(Preloader::class, 'append') && file_exists($preloadFile $buildDir.'/'.$class.'.preload.php')) {
  498.             Preloader::append($preloadFile$preload);
  499.         }
  500.     }
  501.     /**
  502.      * Returns the kernel parameters.
  503.      */
  504.     protected function getKernelParameters(): array
  505.     {
  506.         $bundles = [];
  507.         $bundlesMetadata = [];
  508.         foreach ($this->bundles as $name => $bundle) {
  509.             $bundles[$name] = \get_class($bundle);
  510.             $bundlesMetadata[$name] = [
  511.                 'path' => $bundle->getPath(),
  512.                 'namespace' => $bundle->getNamespace(),
  513.             ];
  514.         }
  515.         return [
  516.             'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  517.             'kernel.environment' => $this->environment,
  518.             'kernel.runtime_environment' => '%env(default:kernel.environment:APP_RUNTIME_ENV)%',
  519.             'kernel.debug' => $this->debug,
  520.             'kernel.build_dir' => realpath($buildDir $this->warmupDir ?: $this->getBuildDir()) ?: $buildDir,
  521.             'kernel.cache_dir' => realpath($cacheDir = ($this->getCacheDir() === $this->getBuildDir() ? ($this->warmupDir ?: $this->getCacheDir()) : $this->getCacheDir())) ?: $cacheDir,
  522.             'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  523.             'kernel.bundles' => $bundles,
  524.             'kernel.bundles_metadata' => $bundlesMetadata,
  525.             'kernel.charset' => $this->getCharset(),
  526.             'kernel.container_class' => $this->getContainerClass(),
  527.         ];
  528.     }
  529.     /**
  530.      * Builds the service container.
  531.      *
  532.      * @throws \RuntimeException
  533.      */
  534.     protected function buildContainer(): ContainerBuilder
  535.     {
  536.         foreach (['cache' => $this->getCacheDir(), 'build' => $this->warmupDir ?: $this->getBuildDir(), 'logs' => $this->getLogDir()] as $name => $dir) {
  537.             if (!is_dir($dir)) {
  538.                 if (false === @mkdir($dir0777true) && !is_dir($dir)) {
  539.                     throw new \RuntimeException(sprintf('Unable to create the "%s" directory (%s).'$name$dir));
  540.                 }
  541.             } elseif (!is_writable($dir)) {
  542.                 throw new \RuntimeException(sprintf('Unable to write in the "%s" directory (%s).'$name$dir));
  543.             }
  544.         }
  545.         $container $this->getContainerBuilder();
  546.         $container->addObjectResource($this);
  547.         $this->prepareContainer($container);
  548.         $this->registerContainerConfiguration($this->getContainerLoader($container));
  549.         $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
  550.         return $container;
  551.     }
  552.     /**
  553.      * Prepares the ContainerBuilder before it is compiled.
  554.      */
  555.     protected function prepareContainer(ContainerBuilder $container)
  556.     {
  557.         $extensions = [];
  558.         foreach ($this->bundles as $bundle) {
  559.             if ($extension $bundle->getContainerExtension()) {
  560.                 $container->registerExtension($extension);
  561.             }
  562.             if ($this->debug) {
  563.                 $container->addObjectResource($bundle);
  564.             }
  565.         }
  566.         foreach ($this->bundles as $bundle) {
  567.             $bundle->build($container);
  568.         }
  569.         $this->build($container);
  570.         foreach ($container->getExtensions() as $extension) {
  571.             $extensions[] = $extension->getAlias();
  572.         }
  573.         // ensure these extensions are implicitly loaded
  574.         $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  575.     }
  576.     /**
  577.      * Gets a new ContainerBuilder instance used to build the service container.
  578.      */
  579.     protected function getContainerBuilder(): ContainerBuilder
  580.     {
  581.         $container = new ContainerBuilder();
  582.         $container->getParameterBag()->add($this->getKernelParameters());
  583.         if ($this instanceof ExtensionInterface) {
  584.             $container->registerExtension($this);
  585.         }
  586.         if ($this instanceof CompilerPassInterface) {
  587.             $container->addCompilerPass($thisPassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
  588.         }
  589.         if (class_exists(\ProxyManager\Configuration::class) && class_exists(RuntimeInstantiator::class)) {
  590.             $container->setProxyInstantiator(new RuntimeInstantiator());
  591.         }
  592.         return $container;
  593.     }
  594.     /**
  595.      * Dumps the service container to PHP code in the cache.
  596.      *
  597.      * @param string $class     The name of the class to generate
  598.      * @param string $baseClass The name of the container's base class
  599.      */
  600.     protected function dumpContainer(ConfigCache $cacheContainerBuilder $containerstring $classstring $baseClass)
  601.     {
  602.         // cache the container
  603.         $dumper = new PhpDumper($container);
  604.         if (class_exists(\ProxyManager\Configuration::class) && class_exists(ProxyDumper::class)) {
  605.             $dumper->setProxyDumper(new ProxyDumper());
  606.         }
  607.         $content $dumper->dump([
  608.             'class' => $class,
  609.             'base_class' => $baseClass,
  610.             'file' => $cache->getPath(),
  611.             'as_files' => true,
  612.             'debug' => $this->debug,
  613.             'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
  614.             'preload_classes' => array_map('get_class'$this->bundles),
  615.         ]);
  616.         $rootCode array_pop($content);
  617.         $dir \dirname($cache->getPath()).'/';
  618.         $fs = new Filesystem();
  619.         foreach ($content as $file => $code) {
  620.             $fs->dumpFile($dir.$file$code);
  621.             @chmod($dir.$file0666 & ~umask());
  622.         }
  623.         $legacyFile \dirname($dir.key($content)).'.legacy';
  624.         if (is_file($legacyFile)) {
  625.             @unlink($legacyFile);
  626.         }
  627.         $cache->write($rootCode$container->getResources());
  628.     }
  629.     /**
  630.      * Returns a loader for the container.
  631.      */
  632.     protected function getContainerLoader(ContainerInterface $container): DelegatingLoader
  633.     {
  634.         $env $this->getEnvironment();
  635.         $locator = new FileLocator($this);
  636.         $resolver = new LoaderResolver([
  637.             new XmlFileLoader($container$locator$env),
  638.             new YamlFileLoader($container$locator$env),
  639.             new IniFileLoader($container$locator$env),
  640.             new PhpFileLoader($container$locator$envclass_exists(ConfigBuilderGenerator::class) ? new ConfigBuilderGenerator($this->getBuildDir()) : null),
  641.             new GlobFileLoader($container$locator$env),
  642.             new DirectoryLoader($container$locator$env),
  643.             new ClosureLoader($container$env),
  644.         ]);
  645.         return new DelegatingLoader($resolver);
  646.     }
  647.     private function preBoot(): ContainerInterface
  648.     {
  649.         if ($this->debug) {
  650.             $this->startTime microtime(true);
  651.         }
  652.         if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
  653.             putenv('SHELL_VERBOSITY=3');
  654.             $_ENV['SHELL_VERBOSITY'] = 3;
  655.             $_SERVER['SHELL_VERBOSITY'] = 3;
  656.         }
  657.         $this->initializeBundles();
  658.         $this->initializeContainer();
  659.         $container $this->container;
  660.         if ($container->hasParameter('kernel.trusted_hosts') && $trustedHosts $container->getParameter('kernel.trusted_hosts')) {
  661.             Request::setTrustedHosts($trustedHosts);
  662.         }
  663.         if ($container->hasParameter('kernel.trusted_proxies') && $container->hasParameter('kernel.trusted_headers') && $trustedProxies $container->getParameter('kernel.trusted_proxies')) {
  664.             Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies array_map('trim'explode(','$trustedProxies)), $container->getParameter('kernel.trusted_headers'));
  665.         }
  666.         return $container;
  667.     }
  668.     /**
  669.      * Removes comments from a PHP source string.
  670.      *
  671.      * We don't use the PHP php_strip_whitespace() function
  672.      * as we want the content to be readable and well-formatted.
  673.      */
  674.     public static function stripComments(string $source): string
  675.     {
  676.         if (!\function_exists('token_get_all')) {
  677.             return $source;
  678.         }
  679.         $rawChunk '';
  680.         $output '';
  681.         $tokens token_get_all($source);
  682.         $ignoreSpace false;
  683.         for ($i 0; isset($tokens[$i]); ++$i) {
  684.             $token $tokens[$i];
  685.             if (!isset($token[1]) || 'b"' === $token) {
  686.                 $rawChunk .= $token;
  687.             } elseif (\T_START_HEREDOC === $token[0]) {
  688.                 $output .= $rawChunk.$token[1];
  689.                 do {
  690.                     $token $tokens[++$i];
  691.                     $output .= isset($token[1]) && 'b"' !== $token $token[1] : $token;
  692.                 } while (\T_END_HEREDOC !== $token[0]);
  693.                 $rawChunk '';
  694.             } elseif (\T_WHITESPACE === $token[0]) {
  695.                 if ($ignoreSpace) {
  696.                     $ignoreSpace false;
  697.                     continue;
  698.                 }
  699.                 // replace multiple new lines with a single newline
  700.                 $rawChunk .= preg_replace(['/\n{2,}/S'], "\n"$token[1]);
  701.             } elseif (\in_array($token[0], [\T_COMMENT\T_DOC_COMMENT])) {
  702.                 if (!\in_array($rawChunk[\strlen($rawChunk) - 1], [' '"\n""\r""\t"], true)) {
  703.                     $rawChunk .= ' ';
  704.                 }
  705.                 $ignoreSpace true;
  706.             } else {
  707.                 $rawChunk .= $token[1];
  708.                 // The PHP-open tag already has a new-line
  709.                 if (\T_OPEN_TAG === $token[0]) {
  710.                     $ignoreSpace true;
  711.                 } else {
  712.                     $ignoreSpace false;
  713.                 }
  714.             }
  715.         }
  716.         $output .= $rawChunk;
  717.         unset($tokens$rawChunk);
  718.         gc_mem_caches();
  719.         return $output;
  720.     }
  721.     public function __sleep(): array
  722.     {
  723.         return ['environment''debug'];
  724.     }
  725.     public function __wakeup()
  726.     {
  727.         if (\is_object($this->environment) || \is_object($this->debug)) {
  728.             throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  729.         }
  730.         $this->__construct($this->environment$this->debug);
  731.     }
  732. }