4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel;
14 use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator;
15 use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17 use Symfony\Component\DependencyInjection\ContainerBuilder;
18 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
19 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
20 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
21 use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
22 use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
23 use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
24 use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
25 use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
26 use Symfony\Component\HttpFoundation\Request;
27 use Symfony\Component\HttpFoundation\Response;
28 use Symfony\Component\HttpKernel\Bundle\BundleInterface;
29 use Symfony\Component\HttpKernel\Config\EnvParametersResource;
30 use Symfony\Component\HttpKernel\Config\FileLocator;
31 use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
32 use Symfony\Component\HttpKernel\DependencyInjection\AddClassesToCachePass;
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;
39 * The Kernel is the heart of the Symfony system.
41 * It manages an environment made of bundles.
43 * @author Fabien Potencier <fabien@symfony.com>
45 abstract class Kernel implements KernelInterface, TerminableInterface
48 * @var BundleInterface[]
50 protected $bundles = array();
55 protected $environment;
57 protected $booted = false;
60 protected $loadClassCache;
62 const VERSION = '2.8.22';
63 const VERSION_ID = 20822;
64 const MAJOR_VERSION = 2;
65 const MINOR_VERSION = 8;
66 const RELEASE_VERSION = 22;
67 const EXTRA_VERSION = '';
69 const END_OF_MAINTENANCE = '11/2018';
70 const END_OF_LIFE = '11/2019';
75 * @param string $environment The environment
76 * @param bool $debug Whether to enable debugging or not
78 public function __construct($environment, $debug)
80 $this->environment = $environment;
81 $this->debug = (bool) $debug;
82 $this->rootDir = $this->getRootDir();
83 $this->name = $this->getName();
86 $this->startTime = microtime(true);
89 $defClass = new \ReflectionMethod($this, 'init');
90 $defClass = $defClass->getDeclaringClass()->name;
92 if (__CLASS__ !== $defClass) {
93 @trigger_error(sprintf('Calling the %s::init() method is deprecated since version 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', $defClass), E_USER_DEPRECATED);
99 * @deprecated since version 2.3, to be removed in 3.0. Move your logic in the constructor instead.
101 public function init()
103 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', E_USER_DEPRECATED);
106 public function __clone()
109 $this->startTime = microtime(true);
112 $this->booted = false;
113 $this->container = null;
117 * Boots the current kernel.
119 public function boot()
121 if (true === $this->booted) {
125 if ($this->loadClassCache) {
126 $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
130 $this->initializeBundles();
133 $this->initializeContainer();
135 foreach ($this->getBundles() as $bundle) {
136 $bundle->setContainer($this->container);
140 $this->booted = true;
146 public function terminate(Request $request, Response $response)
148 if (false === $this->booted) {
152 if ($this->getHttpKernel() instanceof TerminableInterface) {
153 $this->getHttpKernel()->terminate($request, $response);
160 public function shutdown()
162 if (false === $this->booted) {
166 $this->booted = false;
168 foreach ($this->getBundles() as $bundle) {
170 $bundle->setContainer(null);
173 $this->container = null;
179 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
181 if (false === $this->booted) {
185 return $this->getHttpKernel()->handle($request, $type, $catch);
189 * Gets a HTTP kernel from the container.
193 protected function getHttpKernel()
195 return $this->container->get('http_kernel');
201 public function getBundles()
203 return $this->bundles;
209 * @deprecated since version 2.6, to be removed in 3.0.
211 public function isClassInActiveBundle($class)
213 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in version 3.0.', E_USER_DEPRECATED);
215 foreach ($this->getBundles() as $bundle) {
216 if (0 === strpos($class, $bundle->getNamespace())) {
227 public function getBundle($name, $first = true)
229 if (!isset($this->bundleMap[$name])) {
230 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, get_class($this)));
233 if (true === $first) {
234 return $this->bundleMap[$name][0];
237 return $this->bundleMap[$name];
243 * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
245 public function locateResource($name, $dir = null, $first = true)
247 if ('@' !== $name[0]) {
248 throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
251 if (false !== strpos($name, '..')) {
252 throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
255 $bundleName = substr($name, 1);
257 if (false !== strpos($bundleName, '/')) {
258 list($bundleName, $path) = explode('/', $bundleName, 2);
261 $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
262 $overridePath = substr($path, 9);
263 $resourceBundle = null;
264 $bundles = $this->getBundle($bundleName, false);
267 foreach ($bundles as $bundle) {
268 if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
269 if (null !== $resourceBundle) {
270 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.',
273 $dir.'/'.$bundles[0]->getName().$overridePath
283 if (file_exists($file = $bundle->getPath().'/'.$path)) {
284 if ($first && !$isResource) {
288 $resourceBundle = $bundle->getName();
292 if (count($files) > 0) {
293 return $first && $isResource ? $files[0] : $files;
296 throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
302 public function getName()
304 if (null === $this->name) {
305 $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
306 if (ctype_digit($this->name[0])) {
307 $this->name = '_'.$this->name;
317 public function getEnvironment()
319 return $this->environment;
325 public function isDebug()
333 public function getRootDir()
335 if (null === $this->rootDir) {
336 $r = new \ReflectionObject($this);
337 $this->rootDir = dirname($r->getFileName());
340 return $this->rootDir;
346 public function getContainer()
348 return $this->container;
352 * Loads the PHP class cache.
354 * This methods only registers the fact that you want to load the cache classes.
355 * The cache will actually only be loaded when the Kernel is booted.
357 * That optimization is mainly useful when using the HttpCache class in which
358 * case the class cache is not loaded if the Response is in the cache.
360 * @param string $name The cache name prefix
361 * @param string $extension File extension of the resulting file
363 public function loadClassCache($name = 'classes', $extension = '.php')
365 $this->loadClassCache = array($name, $extension);
371 public function setClassCache(array $classes)
373 file_put_contents($this->getCacheDir().'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
379 public function getStartTime()
381 return $this->debug ? $this->startTime : -INF;
387 public function getCacheDir()
389 return $this->rootDir.'/cache/'.$this->environment;
395 public function getLogDir()
397 return $this->rootDir.'/logs';
403 public function getCharset()
408 protected function doLoadClassCache($name, $extension)
410 if (!$this->booted && is_file($this->getCacheDir().'/classes.map')) {
411 ClassCollectionLoader::load(include($this->getCacheDir().'/classes.map'), $this->getCacheDir(), $name, $this->debug, false, $extension);
416 * Initializes the data structures related to the bundle management.
418 * - the bundles property maps a bundle name to the bundle instance,
419 * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
421 * @throws \LogicException if two bundles share a common name
422 * @throws \LogicException if a bundle tries to extend a non-registered bundle
423 * @throws \LogicException if a bundle tries to extend itself
424 * @throws \LogicException if two bundles extend the same ancestor
426 protected function initializeBundles()
429 $this->bundles = array();
430 $topMostBundles = array();
431 $directChildren = array();
433 foreach ($this->registerBundles() as $bundle) {
434 $name = $bundle->getName();
435 if (isset($this->bundles[$name])) {
436 throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
438 $this->bundles[$name] = $bundle;
440 if ($parentName = $bundle->getParent()) {
441 if (isset($directChildren[$parentName])) {
442 throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
444 if ($parentName == $name) {
445 throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
447 $directChildren[$parentName] = $name;
449 $topMostBundles[$name] = $bundle;
454 if (!empty($directChildren) && count($diff = array_diff_key($directChildren, $this->bundles))) {
455 $diff = array_keys($diff);
457 throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
461 $this->bundleMap = array();
462 foreach ($topMostBundles as $name => $bundle) {
463 $bundleMap = array($bundle);
464 $hierarchy = array($name);
466 while (isset($directChildren[$name])) {
467 $name = $directChildren[$name];
468 array_unshift($bundleMap, $this->bundles[$name]);
469 $hierarchy[] = $name;
472 foreach ($hierarchy as $hierarchyBundle) {
473 $this->bundleMap[$hierarchyBundle] = $bundleMap;
474 array_pop($bundleMap);
480 * Gets the container class.
482 * @return string The container class
484 protected function getContainerClass()
486 return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
490 * Gets the container's base class.
492 * All names except Container must be fully qualified.
496 protected function getContainerBaseClass()
502 * Initializes the service container.
504 * The cached version of the service container is used when fresh, otherwise the
505 * container is built.
507 protected function initializeContainer()
509 $class = $this->getContainerClass();
510 $cache = new ConfigCache($this->getCacheDir().'/'.$class.'.php', $this->debug);
512 if (!$cache->isFresh()) {
513 $container = $this->buildContainer();
514 $container->compile();
515 $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
520 require_once $cache->getPath();
522 $this->container = new $class();
523 $this->container->set('kernel', $this);
525 if (!$fresh && $this->container->has('cache_warmer')) {
526 $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
531 * Returns the kernel parameters.
533 * @return array An array of kernel parameters
535 protected function getKernelParameters()
538 $bundlesMetadata = array();
540 foreach ($this->bundles as $name => $bundle) {
541 $bundles[$name] = get_class($bundle);
542 $bundlesMetadata[$name] = array(
543 'parent' => $bundle->getParent(),
544 'path' => $bundle->getPath(),
545 'namespace' => $bundle->getNamespace(),
551 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
552 'kernel.environment' => $this->environment,
553 'kernel.debug' => $this->debug,
554 'kernel.name' => $this->name,
555 'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
556 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
557 'kernel.bundles' => $bundles,
558 'kernel.bundles_metadata' => $bundlesMetadata,
559 'kernel.charset' => $this->getCharset(),
560 'kernel.container_class' => $this->getContainerClass(),
562 $this->getEnvParameters()
567 * Gets the environment parameters.
569 * Only the parameters starting with "SYMFONY__" are considered.
571 * @return array An array of parameters
573 protected function getEnvParameters()
575 $parameters = array();
576 foreach ($_SERVER as $key => $value) {
577 if (0 === strpos($key, 'SYMFONY__')) {
578 $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
586 * Builds the service container.
588 * @return ContainerBuilder The compiled service container
590 * @throws \RuntimeException
592 protected function buildContainer()
594 foreach (array('cache' => $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
596 if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
597 throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
599 } elseif (!is_writable($dir)) {
600 throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
604 $container = $this->getContainerBuilder();
605 $container->addObjectResource($this);
606 $this->prepareContainer($container);
608 if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
609 $container->merge($cont);
612 $container->addCompilerPass(new AddClassesToCachePass($this));
613 $container->addResource(new EnvParametersResource('SYMFONY__'));
619 * Prepares the ContainerBuilder before it is compiled.
621 * @param ContainerBuilder $container A ContainerBuilder instance
623 protected function prepareContainer(ContainerBuilder $container)
625 $extensions = array();
626 foreach ($this->bundles as $bundle) {
627 if ($extension = $bundle->getContainerExtension()) {
628 $container->registerExtension($extension);
629 $extensions[] = $extension->getAlias();
633 $container->addObjectResource($bundle);
636 foreach ($this->bundles as $bundle) {
637 $bundle->build($container);
640 // ensure these extensions are implicitly loaded
641 $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
645 * Gets a new ContainerBuilder instance used to build the service container.
647 * @return ContainerBuilder
649 protected function getContainerBuilder()
651 $container = new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
653 if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
654 $container->setProxyInstantiator(new RuntimeInstantiator());
661 * Dumps the service container to PHP code in the cache.
663 * @param ConfigCache $cache The config cache
664 * @param ContainerBuilder $container The service container
665 * @param string $class The name of the class to generate
666 * @param string $baseClass The name of the container's base class
668 protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
670 // cache the container
671 $dumper = new PhpDumper($container);
673 if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
674 $dumper->setProxyDumper(new ProxyDumper(md5($cache->getPath())));
677 $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass, 'file' => $cache->getPath(), 'debug' => $this->debug));
679 $cache->write($content, $container->getResources());
683 * Returns a loader for the container.
685 * @param ContainerInterface $container The service container
687 * @return DelegatingLoader The loader
689 protected function getContainerLoader(ContainerInterface $container)
691 $locator = new FileLocator($this);
692 $resolver = new LoaderResolver(array(
693 new XmlFileLoader($container, $locator),
694 new YamlFileLoader($container, $locator),
695 new IniFileLoader($container, $locator),
696 new PhpFileLoader($container, $locator),
697 new DirectoryLoader($container, $locator),
698 new ClosureLoader($container),
701 return new DelegatingLoader($resolver);
705 * Removes comments from a PHP source string.
707 * We don't use the PHP php_strip_whitespace() function
708 * as we want the content to be readable and well-formatted.
710 * @param string $source A PHP string
712 * @return string The PHP string with the comments removed
714 public static function stripComments($source)
716 if (!function_exists('token_get_all')) {
722 $tokens = token_get_all($source);
723 $ignoreSpace = false;
724 for ($i = 0; isset($tokens[$i]); ++$i) {
725 $token = $tokens[$i];
726 if (!isset($token[1]) || 'b"' === $token) {
728 } elseif (T_START_HEREDOC === $token[0]) {
729 $output .= $rawChunk.$token[1];
731 $token = $tokens[++$i];
732 $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
733 } while ($token[0] !== T_END_HEREDOC);
735 } elseif (T_WHITESPACE === $token[0]) {
737 $ignoreSpace = false;
742 // replace multiple new lines with a single newline
743 $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
744 } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
747 $rawChunk .= $token[1];
749 // The PHP-open tag already has a new-line
750 if (T_OPEN_TAG === $token[0]) {
756 $output .= $rawChunk;
758 if (\PHP_VERSION_ID >= 70000) {
759 // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
760 unset($tokens, $rawChunk);
767 public function serialize()
769 return serialize(array($this->environment, $this->debug));
772 public function unserialize($data)
774 list($environment, $debug) = unserialize($data);
776 $this->__construct($environment, $debug);