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

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