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

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