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\ClassLoader\ClassCollectionLoader;
17 use Symfony\Component\Config\ConfigCache;
18 use Symfony\Component\Config\Loader\DelegatingLoader;
19 use Symfony\Component\Config\Loader\LoaderResolver;
20 use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
21 use Symfony\Component\DependencyInjection\Compiler\PassConfig;
22 use Symfony\Component\DependencyInjection\ContainerBuilder;
23 use Symfony\Component\DependencyInjection\ContainerInterface;
24 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
25 use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
26 use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
27 use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
28 use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
29 use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
30 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
31 use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
32 use Symfony\Component\Filesystem\Filesystem;
33 use Symfony\Component\HttpFoundation\Request;
34 use Symfony\Component\HttpFoundation\Response;
35 use Symfony\Component\HttpKernel\Bundle\BundleInterface;
36 use Symfony\Component\HttpKernel\Config\EnvParametersResource;
37 use Symfony\Component\HttpKernel\Config\FileLocator;
38 use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
39 use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
42 * The Kernel is the heart of the Symfony system.
44 * It manages an environment made of bundles.
46 * @author Fabien Potencier <fabien@symfony.com>
48 abstract class Kernel implements KernelInterface, RebootableInterface, TerminableInterface
51 * @var BundleInterface[]
53 protected $bundles = array();
58 protected $environment;
60 protected $booted = false;
63 protected $loadClassCache;
67 private $requestStackSize = 0;
68 private $resetServices = false;
70 const VERSION = '3.4.18';
71 const VERSION_ID = 30418;
72 const MAJOR_VERSION = 3;
73 const MINOR_VERSION = 4;
74 const RELEASE_VERSION = 18;
75 const EXTRA_VERSION = '';
77 const END_OF_MAINTENANCE = '11/2020';
78 const END_OF_LIFE = '11/2021';
81 * @param string $environment The environment
82 * @param bool $debug Whether to enable debugging or not
84 public function __construct($environment, $debug)
86 $this->environment = $environment;
87 $this->debug = (bool) $debug;
88 $this->rootDir = $this->getRootDir();
89 $this->name = $this->getName();
92 public function __clone()
94 $this->booted = false;
95 $this->container = null;
96 $this->requestStackSize = 0;
97 $this->resetServices = false;
103 public function boot()
105 if (true === $this->booted) {
106 if (!$this->requestStackSize && $this->resetServices) {
107 if ($this->container->has('services_resetter')) {
108 $this->container->get('services_resetter')->reset();
110 $this->resetServices = false;
112 $this->startTime = microtime(true);
119 $this->startTime = microtime(true);
121 if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
122 putenv('SHELL_VERBOSITY=3');
123 $_ENV['SHELL_VERBOSITY'] = 3;
124 $_SERVER['SHELL_VERBOSITY'] = 3;
127 if ($this->loadClassCache) {
128 $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
132 $this->initializeBundles();
135 $this->initializeContainer();
137 foreach ($this->getBundles() as $bundle) {
138 $bundle->setContainer($this->container);
142 $this->booted = true;
148 public function reboot($warmupDir)
151 $this->warmupDir = $warmupDir;
158 public function terminate(Request $request, Response $response)
160 if (false === $this->booted) {
164 if ($this->getHttpKernel() instanceof TerminableInterface) {
165 $this->getHttpKernel()->terminate($request, $response);
172 public function shutdown()
174 if (false === $this->booted) {
178 $this->booted = false;
180 foreach ($this->getBundles() as $bundle) {
182 $bundle->setContainer(null);
185 $this->container = null;
186 $this->requestStackSize = 0;
187 $this->resetServices = false;
193 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
196 ++$this->requestStackSize;
197 $this->resetServices = true;
200 return $this->getHttpKernel()->handle($request, $type, $catch);
202 --$this->requestStackSize;
207 * Gets a HTTP kernel from the container.
211 protected function getHttpKernel()
213 return $this->container->get('http_kernel');
219 public function getBundles()
221 return $this->bundles;
227 public function getBundle($name, $first = true/*, $noDeprecation = false */)
229 $noDeprecation = false;
230 if (\func_num_args() >= 3) {
231 $noDeprecation = func_get_arg(2);
234 if (!$first && !$noDeprecation) {
235 @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);
238 if (!isset($this->bundleMap[$name])) {
239 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)));
242 if (true === $first) {
243 return $this->bundleMap[$name][0];
246 return $this->bundleMap[$name];
252 * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
254 public function locateResource($name, $dir = null, $first = true)
256 if ('@' !== $name[0]) {
257 throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
260 if (false !== strpos($name, '..')) {
261 throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
264 $bundleName = substr($name, 1);
266 if (false !== strpos($bundleName, '/')) {
267 list($bundleName, $path) = explode('/', $bundleName, 2);
270 $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
271 $overridePath = substr($path, 9);
272 $resourceBundle = null;
273 $bundles = $this->getBundle($bundleName, false, true);
276 foreach ($bundles as $bundle) {
277 if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
278 if (null !== $resourceBundle) {
279 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.', $file, $resourceBundle, $dir.'/'.$bundles[0]->getName().$overridePath));
288 if (file_exists($file = $bundle->getPath().'/'.$path)) {
289 if ($first && !$isResource) {
293 $resourceBundle = $bundle->getName();
297 if (\count($files) > 0) {
298 return $first && $isResource ? $files[0] : $files;
301 throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
307 public function getName()
309 if (null === $this->name) {
310 $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
311 if (ctype_digit($this->name[0])) {
312 $this->name = '_'.$this->name;
322 public function getEnvironment()
324 return $this->environment;
330 public function isDebug()
338 public function getRootDir()
340 if (null === $this->rootDir) {
341 $r = new \ReflectionObject($this);
342 $this->rootDir = \dirname($r->getFileName());
345 return $this->rootDir;
349 * Gets the application root dir (path of the project's composer file).
351 * @return string The project root dir
353 public function getProjectDir()
355 if (null === $this->projectDir) {
356 $r = new \ReflectionObject($this);
357 $dir = $rootDir = \dirname($r->getFileName());
358 while (!file_exists($dir.'/composer.json')) {
359 if ($dir === \dirname($dir)) {
360 return $this->projectDir = $rootDir;
362 $dir = \dirname($dir);
364 $this->projectDir = $dir;
367 return $this->projectDir;
373 public function getContainer()
375 return $this->container;
379 * Loads the PHP class cache.
381 * This methods only registers the fact that you want to load the cache classes.
382 * The cache will actually only be loaded when the Kernel is booted.
384 * That optimization is mainly useful when using the HttpCache class in which
385 * case the class cache is not loaded if the Response is in the cache.
387 * @param string $name The cache name prefix
388 * @param string $extension File extension of the resulting file
390 * @deprecated since version 3.3, to be removed in 4.0. The class cache is not needed anymore when using PHP 7.0.
392 public function loadClassCache($name = 'classes', $extension = '.php')
394 if (\PHP_VERSION_ID >= 70000) {
395 @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
398 $this->loadClassCache = array($name, $extension);
404 * @deprecated since version 3.3, to be removed in 4.0.
406 public function setClassCache(array $classes)
408 if (\PHP_VERSION_ID >= 70000) {
409 @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
412 file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
418 public function setAnnotatedClassCache(array $annotatedClasses)
420 file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/annotations.map', sprintf('<?php return %s;', var_export($annotatedClasses, true)));
426 public function getStartTime()
428 return $this->debug ? $this->startTime : -INF;
434 public function getCacheDir()
436 return $this->rootDir.'/cache/'.$this->environment;
442 public function getLogDir()
444 return $this->rootDir.'/logs';
450 public function getCharset()
456 * @deprecated since version 3.3, to be removed in 4.0.
458 protected function doLoadClassCache($name, $extension)
460 if (\PHP_VERSION_ID >= 70000) {
461 @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
463 $cacheDir = $this->warmupDir ?: $this->getCacheDir();
465 if (!$this->booted && is_file($cacheDir.'/classes.map')) {
466 ClassCollectionLoader::load(include($cacheDir.'/classes.map'), $cacheDir, $name, $this->debug, false, $extension);
471 * Initializes the data structures related to the bundle management.
473 * - the bundles property maps a bundle name to the bundle instance,
474 * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
476 * @throws \LogicException if two bundles share a common name
477 * @throws \LogicException if a bundle tries to extend a non-registered bundle
478 * @throws \LogicException if a bundle tries to extend itself
479 * @throws \LogicException if two bundles extend the same ancestor
481 protected function initializeBundles()
484 $this->bundles = array();
485 $topMostBundles = array();
486 $directChildren = array();
488 foreach ($this->registerBundles() as $bundle) {
489 $name = $bundle->getName();
490 if (isset($this->bundles[$name])) {
491 throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
493 $this->bundles[$name] = $bundle;
495 if ($parentName = $bundle->getParent()) {
496 @trigger_error('Bundle inheritance is deprecated as of 3.4 and will be removed in 4.0.', E_USER_DEPRECATED);
498 if (isset($directChildren[$parentName])) {
499 throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
501 if ($parentName == $name) {
502 throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
504 $directChildren[$parentName] = $name;
506 $topMostBundles[$name] = $bundle;
511 if (!empty($directChildren) && \count($diff = array_diff_key($directChildren, $this->bundles))) {
512 $diff = array_keys($diff);
514 throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
518 $this->bundleMap = array();
519 foreach ($topMostBundles as $name => $bundle) {
520 $bundleMap = array($bundle);
521 $hierarchy = array($name);
523 while (isset($directChildren[$name])) {
524 $name = $directChildren[$name];
525 array_unshift($bundleMap, $this->bundles[$name]);
526 $hierarchy[] = $name;
529 foreach ($hierarchy as $hierarchyBundle) {
530 $this->bundleMap[$hierarchyBundle] = $bundleMap;
531 array_pop($bundleMap);
537 * The extension point similar to the Bundle::build() method.
539 * Use this method to register compiler passes and manipulate the container during the building process.
541 protected function build(ContainerBuilder $container)
546 * Gets the container class.
548 * @return string The container class
550 protected function getContainerClass()
552 return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
556 * Gets the container's base class.
558 * All names except Container must be fully qualified.
562 protected function getContainerBaseClass()
568 * Initializes the service container.
570 * The cached version of the service container is used when fresh, otherwise the
571 * container is built.
573 protected function initializeContainer()
575 $class = $this->getContainerClass();
576 $cacheDir = $this->warmupDir ?: $this->getCacheDir();
577 $cache = new ConfigCache($cacheDir.'/'.$class.'.php', $this->debug);
578 $oldContainer = null;
579 if ($fresh = $cache->isFresh()) {
580 // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
581 $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
582 $fresh = $oldContainer = false;
584 if (file_exists($cache->getPath()) && \is_object($this->container = include $cache->getPath())) {
585 $this->container->set('kernel', $this);
586 $oldContainer = $this->container;
589 } catch (\Throwable $e) {
590 } catch (\Exception $e) {
592 error_reporting($errorLevel);
601 $collectedLogs = array();
602 $previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL');
603 $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
604 if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
605 return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
608 if (isset($collectedLogs[$message])) {
609 ++$collectedLogs[$message]['count'];
614 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
615 // Clean the trace by removing first frames added by the error handler itself.
616 for ($i = 0; isset($backtrace[$i]); ++$i) {
617 if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
618 $backtrace = \array_slice($backtrace, 1 + $i);
623 $collectedLogs[$message] = array(
625 'message' => $message,
628 'trace' => $backtrace,
636 $container = $this->buildContainer();
637 $container->compile();
639 if ($this->debug && true !== $previousHandler) {
640 restore_error_handler();
642 file_put_contents($cacheDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
643 file_put_contents($cacheDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
647 if (null === $oldContainer && file_exists($cache->getPath())) {
648 $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
650 $oldContainer = include $cache->getPath();
651 } catch (\Throwable $e) {
652 } catch (\Exception $e) {
654 error_reporting($errorLevel);
657 $oldContainer = \is_object($oldContainer) ? new \ReflectionClass($oldContainer) : false;
659 $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
660 $this->container = require $cache->getPath();
661 $this->container->set('kernel', $this);
663 if ($oldContainer && \get_class($this->container) !== $oldContainer->name) {
664 // Because concurrent requests might still be using them,
665 // old container files are not removed immediately,
666 // but on a next dump of the container.
667 static $legacyContainers = array();
668 $oldContainerDir = \dirname($oldContainer->getFileName());
669 $legacyContainers[$oldContainerDir.'.legacy'] = true;
670 foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) {
671 if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
672 (new Filesystem())->remove(substr($legacyContainer, 0, -7));
676 touch($oldContainerDir.'.legacy');
679 if ($this->container->has('cache_warmer')) {
680 $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
685 * Returns the kernel parameters.
687 * @return array An array of kernel parameters
689 protected function getKernelParameters()
692 $bundlesMetadata = array();
694 foreach ($this->bundles as $name => $bundle) {
695 $bundles[$name] = \get_class($bundle);
696 $bundlesMetadata[$name] = array(
697 'parent' => $bundle->getParent(),
698 'path' => $bundle->getPath(),
699 'namespace' => $bundle->getNamespace(),
705 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
706 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
707 'kernel.environment' => $this->environment,
708 'kernel.debug' => $this->debug,
709 'kernel.name' => $this->name,
710 'kernel.cache_dir' => realpath($cacheDir = $this->warmupDir ?: $this->getCacheDir()) ?: $cacheDir,
711 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
712 'kernel.bundles' => $bundles,
713 'kernel.bundles_metadata' => $bundlesMetadata,
714 'kernel.charset' => $this->getCharset(),
715 'kernel.container_class' => $this->getContainerClass(),
717 $this->getEnvParameters(false)
722 * Gets the environment parameters.
724 * Only the parameters starting with "SYMFONY__" are considered.
726 * @return array An array of parameters
728 * @deprecated since version 3.3, to be removed in 4.0
730 protected function getEnvParameters()
732 if (0 === \func_num_args() || func_get_arg(0)) {
733 @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);
736 $parameters = array();
737 foreach ($_SERVER as $key => $value) {
738 if (0 === strpos($key, 'SYMFONY__')) {
739 @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);
740 $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
748 * Builds the service container.
750 * @return ContainerBuilder The compiled service container
752 * @throws \RuntimeException
754 protected function buildContainer()
756 foreach (array('cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
758 if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
759 throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
761 } elseif (!is_writable($dir)) {
762 throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
766 $container = $this->getContainerBuilder();
767 $container->addObjectResource($this);
768 $this->prepareContainer($container);
770 if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
771 $container->merge($cont);
774 $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
775 $container->addResource(new EnvParametersResource('SYMFONY__'));
781 * Prepares the ContainerBuilder before it is compiled.
783 protected function prepareContainer(ContainerBuilder $container)
785 $extensions = array();
786 foreach ($this->bundles as $bundle) {
787 if ($extension = $bundle->getContainerExtension()) {
788 $container->registerExtension($extension);
792 $container->addObjectResource($bundle);
796 foreach ($this->bundles as $bundle) {
797 $bundle->build($container);
800 $this->build($container);
802 foreach ($container->getExtensions() as $extension) {
803 $extensions[] = $extension->getAlias();
806 // ensure these extensions are implicitly loaded
807 $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
811 * Gets a new ContainerBuilder instance used to build the service container.
813 * @return ContainerBuilder
815 protected function getContainerBuilder()
817 $container = new ContainerBuilder();
818 $container->getParameterBag()->add($this->getKernelParameters());
820 if ($this instanceof CompilerPassInterface) {
821 $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
823 if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
824 $container->setProxyInstantiator(new RuntimeInstantiator());
831 * Dumps the service container to PHP code in the cache.
833 * @param ConfigCache $cache The config cache
834 * @param ContainerBuilder $container The service container
835 * @param string $class The name of the class to generate
836 * @param string $baseClass The name of the container's base class
838 protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
840 // cache the container
841 $dumper = new PhpDumper($container);
843 if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
844 $dumper->setProxyDumper(new ProxyDumper());
847 $content = $dumper->dump(array(
849 'base_class' => $baseClass,
850 'file' => $cache->getPath(),
852 'debug' => $this->debug,
853 'inline_class_loader_parameter' => \PHP_VERSION_ID >= 70000 && !$this->loadClassCache && !class_exists(ClassCollectionLoader::class, false) ? 'container.dumper.inline_class_loader' : null,
854 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
857 $rootCode = array_pop($content);
858 $dir = \dirname($cache->getPath()).'/';
859 $fs = new Filesystem();
861 foreach ($content as $file => $code) {
862 $fs->dumpFile($dir.$file, $code);
863 @chmod($dir.$file, 0666 & ~umask());
865 @unlink(\dirname($dir.$file).'.legacy');
867 $cache->write($rootCode, $container->getResources());
871 * Returns a loader for the container.
873 * @return DelegatingLoader The loader
875 protected function getContainerLoader(ContainerInterface $container)
877 $locator = new FileLocator($this);
878 $resolver = new LoaderResolver(array(
879 new XmlFileLoader($container, $locator),
880 new YamlFileLoader($container, $locator),
881 new IniFileLoader($container, $locator),
882 new PhpFileLoader($container, $locator),
883 new GlobFileLoader($container, $locator),
884 new DirectoryLoader($container, $locator),
885 new ClosureLoader($container),
888 return new DelegatingLoader($resolver);
892 * Removes comments from a PHP source string.
894 * We don't use the PHP php_strip_whitespace() function
895 * as we want the content to be readable and well-formatted.
897 * @param string $source A PHP string
899 * @return string The PHP string with the comments removed
901 public static function stripComments($source)
903 if (!\function_exists('token_get_all')) {
909 $tokens = token_get_all($source);
910 $ignoreSpace = false;
911 for ($i = 0; isset($tokens[$i]); ++$i) {
912 $token = $tokens[$i];
913 if (!isset($token[1]) || 'b"' === $token) {
915 } elseif (T_START_HEREDOC === $token[0]) {
916 $output .= $rawChunk.$token[1];
918 $token = $tokens[++$i];
919 $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
920 } while (T_END_HEREDOC !== $token[0]);
922 } elseif (T_WHITESPACE === $token[0]) {
924 $ignoreSpace = false;
929 // replace multiple new lines with a single newline
930 $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
931 } elseif (\in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
934 $rawChunk .= $token[1];
936 // The PHP-open tag already has a new-line
937 if (T_OPEN_TAG === $token[0]) {
943 $output .= $rawChunk;
945 if (\PHP_VERSION_ID >= 70000) {
946 // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
947 unset($tokens, $rawChunk);
954 public function serialize()
956 return serialize(array($this->environment, $this->debug));
959 public function unserialize($data)
961 if (\PHP_VERSION_ID >= 70000) {
962 list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
964 list($environment, $debug) = unserialize($data);
967 $this->__construct($environment, $debug);