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

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