vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php line 165

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