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

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