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

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