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.13';
  72.     const VERSION_ID 40413;
  73.     const MAJOR_VERSION 4;
  74.     const MINOR_VERSION 4;
  75.     const RELEASE_VERSION 13;
  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.             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 (false !== strpos($name'..')) {
  225.             throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).'$name));
  226.         }
  227.         $bundleName substr($name1);
  228.         $path '';
  229.         if (false !== strpos($bundleName'/')) {
  230.             list($bundleName$path) = explode('/'$bundleName2);
  231.         }
  232.         $isResource === strpos($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 false !== strpos($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.                 flock($lockLOCK_EX LOCK_NB$wouldBlock);
  458.                 if (!flock($lock$wouldBlock LOCK_SH LOCK_EX)) {
  459.                     fclose($lock);
  460.                     $lock null;
  461.                 } elseif (!\is_object($this->container = include $cachePath)) {
  462.                     $this->container null;
  463.                 } elseif (!$oldContainer || \get_class($this->container) !== $oldContainer->name) {
  464.                     flock($lockLOCK_UN);
  465.                     fclose($lock);
  466.                     $this->container->set('kernel'$this);
  467.                     return;
  468.                 }
  469.             }
  470.         } catch (\Throwable $e) {
  471.         } finally {
  472.             error_reporting($errorLevel);
  473.         }
  474.         if ($collectDeprecations $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) {
  475.             $collectedLogs = [];
  476.             $previousHandler set_error_handler(function ($type$message$file$line) use (&$collectedLogs, &$previousHandler) {
  477.                 if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
  478.                     return $previousHandler $previousHandler($type$message$file$line) : false;
  479.                 }
  480.                 if (isset($collectedLogs[$message])) {
  481.                     ++$collectedLogs[$message]['count'];
  482.                     return null;
  483.                 }
  484.                 $backtrace debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS5);
  485.                 // Clean the trace by removing first frames added by the error handler itself.
  486.                 for ($i 0; isset($backtrace[$i]); ++$i) {
  487.                     if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  488.                         $backtrace = \array_slice($backtrace$i);
  489.                         break;
  490.                     }
  491.                 }
  492.                 // Remove frames added by DebugClassLoader.
  493.                 for ($i = \count($backtrace) - 2$i; --$i) {
  494.                     if (\in_array($backtrace[$i]['class'] ?? null, [DebugClassLoader::class, LegacyDebugClassLoader::class], true)) {
  495.                         $backtrace = [$backtrace[$i 1]];
  496.                         break;
  497.                     }
  498.                 }
  499.                 $collectedLogs[$message] = [
  500.                     'type' => $type,
  501.                     'message' => $message,
  502.                     'file' => $file,
  503.                     'line' => $line,
  504.                     'trace' => [$backtrace[0]],
  505.                     'count' => 1,
  506.                 ];
  507.                 return null;
  508.             });
  509.         }
  510.         try {
  511.             $container null;
  512.             $container $this->buildContainer();
  513.             $container->compile();
  514.         } finally {
  515.             if ($collectDeprecations) {
  516.                 restore_error_handler();
  517.                 file_put_contents($cacheDir.'/'.$class.'Deprecations.log'serialize(array_values($collectedLogs)));
  518.                 file_put_contents($cacheDir.'/'.$class.'Compiler.log'null !== $container implode("\n"$container->getCompiler()->getLog()) : '');
  519.             }
  520.         }
  521.         $this->dumpContainer($cache$container$class$this->getContainerBaseClass());
  522.         if ($lock) {
  523.             flock($lockLOCK_UN);
  524.             fclose($lock);
  525.         }
  526.         $this->container = require $cachePath;
  527.         $this->container->set('kernel'$this);
  528.         if ($oldContainer && \get_class($this->container) !== $oldContainer->name) {
  529.             // Because concurrent requests might still be using them,
  530.             // old container files are not removed immediately,
  531.             // but on a next dump of the container.
  532.             static $legacyContainers = [];
  533.             $oldContainerDir = \dirname($oldContainer->getFileName());
  534.             $legacyContainers[$oldContainerDir.'.legacy'] = true;
  535.             foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy'GLOB_NOSORT) as $legacyContainer) {
  536.                 if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
  537.                     (new Filesystem())->remove(substr($legacyContainer0, -7));
  538.                 }
  539.             }
  540.             touch($oldContainerDir.'.legacy');
  541.         }
  542.         if ($this->container->has('cache_warmer')) {
  543.             $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  544.         }
  545.     }
  546.     /**
  547.      * Returns the kernel parameters.
  548.      *
  549.      * @return array An array of kernel parameters
  550.      */
  551.     protected function getKernelParameters()
  552.     {
  553.         $bundles = [];
  554.         $bundlesMetadata = [];
  555.         foreach ($this->bundles as $name => $bundle) {
  556.             $bundles[$name] = \get_class($bundle);
  557.             $bundlesMetadata[$name] = [
  558.                 'path' => $bundle->getPath(),
  559.                 'namespace' => $bundle->getNamespace(),
  560.             ];
  561.         }
  562.         return [
  563.             /*
  564.              * @deprecated since Symfony 4.2, use kernel.project_dir instead
  565.              */
  566.             'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
  567.             'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  568.             'kernel.environment' => $this->environment,
  569.             'kernel.debug' => $this->debug,
  570.             /*
  571.              * @deprecated since Symfony 4.2
  572.              */
  573.             'kernel.name' => $this->name,
  574.             'kernel.cache_dir' => realpath($cacheDir $this->warmupDir ?: $this->getCacheDir()) ?: $cacheDir,
  575.             'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  576.             'kernel.bundles' => $bundles,
  577.             'kernel.bundles_metadata' => $bundlesMetadata,
  578.             'kernel.charset' => $this->getCharset(),
  579.             'kernel.container_class' => $this->getContainerClass(),
  580.         ];
  581.     }
  582.     /**
  583.      * Builds the service container.
  584.      *
  585.      * @return ContainerBuilder The compiled service container
  586.      *
  587.      * @throws \RuntimeException
  588.      */
  589.     protected function buildContainer()
  590.     {
  591.         foreach (['cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()] as $name => $dir) {
  592.             if (!is_dir($dir)) {
  593.                 if (false === @mkdir($dir0777true) && !is_dir($dir)) {
  594.                     throw new \RuntimeException(sprintf('Unable to create the "%s" directory (%s).'$name$dir));
  595.                 }
  596.             } elseif (!is_writable($dir)) {
  597.                 throw new \RuntimeException(sprintf('Unable to write in the "%s" directory (%s).'$name$dir));
  598.             }
  599.         }
  600.         $container $this->getContainerBuilder();
  601.         $container->addObjectResource($this);
  602.         $this->prepareContainer($container);
  603.         if (null !== $cont $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  604.             $container->merge($cont);
  605.         }
  606.         $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
  607.         return $container;
  608.     }
  609.     /**
  610.      * Prepares the ContainerBuilder before it is compiled.
  611.      */
  612.     protected function prepareContainer(ContainerBuilder $container)
  613.     {
  614.         $extensions = [];
  615.         foreach ($this->bundles as $bundle) {
  616.             if ($extension $bundle->getContainerExtension()) {
  617.                 $container->registerExtension($extension);
  618.             }
  619.             if ($this->debug) {
  620.                 $container->addObjectResource($bundle);
  621.             }
  622.         }
  623.         foreach ($this->bundles as $bundle) {
  624.             $bundle->build($container);
  625.         }
  626.         $this->build($container);
  627.         foreach ($container->getExtensions() as $extension) {
  628.             $extensions[] = $extension->getAlias();
  629.         }
  630.         // ensure these extensions are implicitly loaded
  631.         $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  632.     }
  633.     /**
  634.      * Gets a new ContainerBuilder instance used to build the service container.
  635.      *
  636.      * @return ContainerBuilder
  637.      */
  638.     protected function getContainerBuilder()
  639.     {
  640.         $container = new ContainerBuilder();
  641.         $container->getParameterBag()->add($this->getKernelParameters());
  642.         if ($this instanceof CompilerPassInterface) {
  643.             $container->addCompilerPass($thisPassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
  644.         }
  645.         if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
  646.             $container->setProxyInstantiator(new RuntimeInstantiator());
  647.         }
  648.         return $container;
  649.     }
  650.     /**
  651.      * Dumps the service container to PHP code in the cache.
  652.      *
  653.      * @param string $class     The name of the class to generate
  654.      * @param string $baseClass The name of the container's base class
  655.      */
  656.     protected function dumpContainer(ConfigCache $cacheContainerBuilder $container$class$baseClass)
  657.     {
  658.         // cache the container
  659.         $dumper = new PhpDumper($container);
  660.         if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
  661.             $dumper->setProxyDumper(new ProxyDumper());
  662.         }
  663.         $content $dumper->dump([
  664.             'class' => $class,
  665.             'base_class' => $baseClass,
  666.             'file' => $cache->getPath(),
  667.             'as_files' => true,
  668.             'debug' => $this->debug,
  669.             'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
  670.             'preload_classes' => array_map('get_class'$this->bundles),
  671.         ]);
  672.         $rootCode array_pop($content);
  673.         $dir = \dirname($cache->getPath()).'/';
  674.         $fs = new Filesystem();
  675.         foreach ($content as $file => $code) {
  676.             $fs->dumpFile($dir.$file$code);
  677.             @chmod($dir.$file0666 & ~umask());
  678.         }
  679.         $legacyFile = \dirname($dir.key($content)).'.legacy';
  680.         if (file_exists($legacyFile)) {
  681.             @unlink($legacyFile);
  682.         }
  683.         $cache->write($rootCode$container->getResources());
  684.     }
  685.     /**
  686.      * Returns a loader for the container.
  687.      *
  688.      * @return DelegatingLoader The loader
  689.      */
  690.     protected function getContainerLoader(ContainerInterface $container)
  691.     {
  692.         $locator = new FileLocator($this);
  693.         $resolver = new LoaderResolver([
  694.             new XmlFileLoader($container$locator),
  695.             new YamlFileLoader($container$locator),
  696.             new IniFileLoader($container$locator),
  697.             new PhpFileLoader($container$locator),
  698.             new GlobFileLoader($container$locator),
  699.             new DirectoryLoader($container$locator),
  700.             new ClosureLoader($container),
  701.         ]);
  702.         return new DelegatingLoader($resolver);
  703.     }
  704.     /**
  705.      * Removes comments from a PHP source string.
  706.      *
  707.      * We don't use the PHP php_strip_whitespace() function
  708.      * as we want the content to be readable and well-formatted.
  709.      *
  710.      * @param string $source A PHP string
  711.      *
  712.      * @return string The PHP string with the comments removed
  713.      */
  714.     public static function stripComments($source)
  715.     {
  716.         if (!\function_exists('token_get_all')) {
  717.             return $source;
  718.         }
  719.         $rawChunk '';
  720.         $output '';
  721.         $tokens token_get_all($source);
  722.         $ignoreSpace false;
  723.         for ($i 0; isset($tokens[$i]); ++$i) {
  724.             $token $tokens[$i];
  725.             if (!isset($token[1]) || 'b"' === $token) {
  726.                 $rawChunk .= $token;
  727.             } elseif (T_START_HEREDOC === $token[0]) {
  728.                 $output .= $rawChunk.$token[1];
  729.                 do {
  730.                     $token $tokens[++$i];
  731.                     $output .= isset($token[1]) && 'b"' !== $token $token[1] : $token;
  732.                 } while (T_END_HEREDOC !== $token[0]);
  733.                 $rawChunk '';
  734.             } elseif (T_WHITESPACE === $token[0]) {
  735.                 if ($ignoreSpace) {
  736.                     $ignoreSpace false;
  737.                     continue;
  738.                 }
  739.                 // replace multiple new lines with a single newline
  740.                 $rawChunk .= preg_replace(['/\n{2,}/S'], "\n"$token[1]);
  741.             } elseif (\in_array($token[0], [T_COMMENTT_DOC_COMMENT])) {
  742.                 $ignoreSpace true;
  743.             } else {
  744.                 $rawChunk .= $token[1];
  745.                 // The PHP-open tag already has a new-line
  746.                 if (T_OPEN_TAG === $token[0]) {
  747.                     $ignoreSpace true;
  748.                 }
  749.             }
  750.         }
  751.         $output .= $rawChunk;
  752.         unset($tokens$rawChunk);
  753.         gc_mem_caches();
  754.         return $output;
  755.     }
  756.     /**
  757.      * @deprecated since Symfony 4.3
  758.      */
  759.     public function serialize()
  760.     {
  761.         @trigger_error(sprintf('The "%s" method is deprecated since Symfony 4.3.'__METHOD__), E_USER_DEPRECATED);
  762.         return serialize([$this->environment$this->debug]);
  763.     }
  764.     /**
  765.      * @deprecated since Symfony 4.3
  766.      */
  767.     public function unserialize($data)
  768.     {
  769.         @trigger_error(sprintf('The "%s" method is deprecated since Symfony 4.3.'__METHOD__), E_USER_DEPRECATED);
  770.         list($environment$debug) = unserialize($data, ['allowed_classes' => false]);
  771.         $this->__construct($environment$debug);
  772.     }
  773.     /**
  774.      * @return array
  775.      */
  776.     public function __sleep()
  777.     {
  778.         if (__CLASS__ !== $c = (new \ReflectionMethod($this'serialize'))->getDeclaringClass()->name) {
  779.             @trigger_error(sprintf('Implementing the "%s::serialize()" method is deprecated since Symfony 4.3.'$c), E_USER_DEPRECATED);
  780.             $this->serialized $this->serialize();
  781.             return ['serialized'];
  782.         }
  783.         return ['environment''debug'];
  784.     }
  785.     public function __wakeup()
  786.     {
  787.         if (__CLASS__ !== $c = (new \ReflectionMethod($this'serialize'))->getDeclaringClass()->name) {
  788.             @trigger_error(sprintf('Implementing the "%s::serialize()" method is deprecated since Symfony 4.3.'$c), E_USER_DEPRECATED);
  789.             $this->unserialize($this->serialized);
  790.             unset($this->serialized);
  791.             return;
  792.         }
  793.         $this->__construct($this->environment$this->debug);
  794.     }
  795. }