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

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