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\Compiler\CompilerPassInterface;
17 use Symfony\Component\DependencyInjection\Compiler\PassConfig;
18 use Symfony\Component\DependencyInjection\ContainerInterface;
19 use Symfony\Component\DependencyInjection\ContainerBuilder;
20 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
21 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
22 use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
23 use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
24 use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
25 use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
26 use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
27 use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
28 use Symfony\Component\Filesystem\Filesystem;
29 use Symfony\Component\HttpFoundation\Request;
30 use Symfony\Component\HttpFoundation\Response;
31 use Symfony\Component\HttpKernel\Bundle\BundleInterface;
32 use Symfony\Component\HttpKernel\Config\EnvParametersResource;
33 use Symfony\Component\HttpKernel\Config\FileLocator;
34 use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
35 use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
36 use Symfony\Component\Config\Loader\LoaderResolver;
37 use Symfony\Component\Config\Loader\DelegatingLoader;
38 use Symfony\Component\Config\ConfigCache;
39 use Symfony\Component\ClassLoader\ClassCollectionLoader;
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.9';
71 const VERSION_ID = 30409;
72 const MAJOR_VERSION = 3;
73 const MINOR_VERSION = 4;
74 const RELEASE_VERSION = 9;
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 $this->startTime = microtime(true);
96 public function __clone()
99 $this->startTime = microtime(true);
102 $this->booted = false;
103 $this->container = null;
104 $this->requestStackSize = 0;
105 $this->resetServices = false;
109 * Boots the current kernel.
111 public function boot()
113 if (true === $this->booted) {
114 if (!$this->requestStackSize && $this->resetServices) {
115 if ($this->container->has('services_resetter')) {
116 $this->container->get('services_resetter')->reset();
118 $this->resetServices = false;
123 if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
124 putenv('SHELL_VERBOSITY=3');
125 $_ENV['SHELL_VERBOSITY'] = 3;
126 $_SERVER['SHELL_VERBOSITY'] = 3;
129 if ($this->loadClassCache) {
130 $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
134 $this->initializeBundles();
137 $this->initializeContainer();
139 foreach ($this->getBundles() as $bundle) {
140 $bundle->setContainer($this->container);
144 $this->booted = true;
150 public function reboot($warmupDir)
153 $this->warmupDir = $warmupDir;
160 public function terminate(Request $request, Response $response)
162 if (false === $this->booted) {
166 if ($this->getHttpKernel() instanceof TerminableInterface) {
167 $this->getHttpKernel()->terminate($request, $response);
174 public function shutdown()
176 if (false === $this->booted) {
180 $this->booted = false;
182 foreach ($this->getBundles() as $bundle) {
184 $bundle->setContainer(null);
187 $this->container = null;
188 $this->requestStackSize = 0;
189 $this->resetServices = false;
195 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
198 ++$this->requestStackSize;
199 $this->resetServices = true;
202 return $this->getHttpKernel()->handle($request, $type, $catch);
204 --$this->requestStackSize;
209 * Gets a HTTP kernel from the container.
213 protected function getHttpKernel()
215 return $this->container->get('http_kernel');
221 public function getBundles()
223 return $this->bundles;
229 public function getBundle($name, $first = true/*, $noDeprecation = false */)
231 $noDeprecation = false;
232 if (func_num_args() >= 3) {
233 $noDeprecation = func_get_arg(2);
236 if (!$first && !$noDeprecation) {
237 @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);
240 if (!isset($this->bundleMap[$name])) {
241 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)));
244 if (true === $first) {
245 return $this->bundleMap[$name][0];
248 return $this->bundleMap[$name];
254 * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
256 public function locateResource($name, $dir = null, $first = true)
258 if ('@' !== $name[0]) {
259 throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
262 if (false !== strpos($name, '..')) {
263 throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
266 $bundleName = substr($name, 1);
268 if (false !== strpos($bundleName, '/')) {
269 list($bundleName, $path) = explode('/', $bundleName, 2);
272 $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
273 $overridePath = substr($path, 9);
274 $resourceBundle = null;
275 $bundles = $this->getBundle($bundleName, false, true);
278 foreach ($bundles as $bundle) {
279 if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
280 if (null !== $resourceBundle) {
281 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.',
284 $dir.'/'.$bundles[0]->getName().$overridePath
294 if (file_exists($file = $bundle->getPath().'/'.$path)) {
295 if ($first && !$isResource) {
299 $resourceBundle = $bundle->getName();
303 if (count($files) > 0) {
304 return $first && $isResource ? $files[0] : $files;
307 throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
313 public function getName()
315 if (null === $this->name) {
316 $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
317 if (ctype_digit($this->name[0])) {
318 $this->name = '_'.$this->name;
328 public function getEnvironment()
330 return $this->environment;
336 public function isDebug()
344 public function getRootDir()
346 if (null === $this->rootDir) {
347 $r = new \ReflectionObject($this);
348 $this->rootDir = dirname($r->getFileName());
351 return $this->rootDir;
355 * Gets the application root dir (path of the project's composer file).
357 * @return string The project root dir
359 public function getProjectDir()
361 if (null === $this->projectDir) {
362 $r = new \ReflectionObject($this);
363 $dir = $rootDir = dirname($r->getFileName());
364 while (!file_exists($dir.'/composer.json')) {
365 if ($dir === dirname($dir)) {
366 return $this->projectDir = $rootDir;
368 $dir = dirname($dir);
370 $this->projectDir = $dir;
373 return $this->projectDir;
379 public function getContainer()
381 return $this->container;
385 * Loads the PHP class cache.
387 * This methods only registers the fact that you want to load the cache classes.
388 * The cache will actually only be loaded when the Kernel is booted.
390 * That optimization is mainly useful when using the HttpCache class in which
391 * case the class cache is not loaded if the Response is in the cache.
393 * @param string $name The cache name prefix
394 * @param string $extension File extension of the resulting file
396 * @deprecated since version 3.3, to be removed in 4.0. The class cache is not needed anymore when using PHP 7.0.
398 public function loadClassCache($name = 'classes', $extension = '.php')
400 if (\PHP_VERSION_ID >= 70000) {
401 @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
404 $this->loadClassCache = array($name, $extension);
410 * @deprecated since version 3.3, to be removed in 4.0.
412 public function setClassCache(array $classes)
414 if (\PHP_VERSION_ID >= 70000) {
415 @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
418 file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
424 public function setAnnotatedClassCache(array $annotatedClasses)
426 file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/annotations.map', sprintf('<?php return %s;', var_export($annotatedClasses, true)));
432 public function getStartTime()
434 return $this->debug ? $this->startTime : -INF;
440 public function getCacheDir()
442 return $this->rootDir.'/cache/'.$this->environment;
448 public function getLogDir()
450 return $this->rootDir.'/logs';
456 public function getCharset()
462 * @deprecated since version 3.3, to be removed in 4.0.
464 protected function doLoadClassCache($name, $extension)
466 if (\PHP_VERSION_ID >= 70000) {
467 @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
469 $cacheDir = $this->warmupDir ?: $this->getCacheDir();
471 if (!$this->booted && is_file($cacheDir.'/classes.map')) {
472 ClassCollectionLoader::load(include($cacheDir.'/classes.map'), $cacheDir, $name, $this->debug, false, $extension);
477 * Initializes the data structures related to the bundle management.
479 * - the bundles property maps a bundle name to the bundle instance,
480 * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
482 * @throws \LogicException if two bundles share a common name
483 * @throws \LogicException if a bundle tries to extend a non-registered bundle
484 * @throws \LogicException if a bundle tries to extend itself
485 * @throws \LogicException if two bundles extend the same ancestor
487 protected function initializeBundles()
490 $this->bundles = array();
491 $topMostBundles = array();
492 $directChildren = array();
494 foreach ($this->registerBundles() as $bundle) {
495 $name = $bundle->getName();
496 if (isset($this->bundles[$name])) {
497 throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
499 $this->bundles[$name] = $bundle;
501 if ($parentName = $bundle->getParent()) {
502 @trigger_error('Bundle inheritance is deprecated as of 3.4 and will be removed in 4.0.', E_USER_DEPRECATED);
504 if (isset($directChildren[$parentName])) {
505 throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
507 if ($parentName == $name) {
508 throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
510 $directChildren[$parentName] = $name;
512 $topMostBundles[$name] = $bundle;
517 if (!empty($directChildren) && count($diff = array_diff_key($directChildren, $this->bundles))) {
518 $diff = array_keys($diff);
520 throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
524 $this->bundleMap = array();
525 foreach ($topMostBundles as $name => $bundle) {
526 $bundleMap = array($bundle);
527 $hierarchy = array($name);
529 while (isset($directChildren[$name])) {
530 $name = $directChildren[$name];
531 array_unshift($bundleMap, $this->bundles[$name]);
532 $hierarchy[] = $name;
535 foreach ($hierarchy as $hierarchyBundle) {
536 $this->bundleMap[$hierarchyBundle] = $bundleMap;
537 array_pop($bundleMap);
543 * The extension point similar to the Bundle::build() method.
545 * Use this method to register compiler passes and manipulate the container during the building process.
547 protected function build(ContainerBuilder $container)
552 * Gets the container class.
554 * @return string The container class
556 protected function getContainerClass()
558 return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
562 * Gets the container's base class.
564 * All names except Container must be fully qualified.
568 protected function getContainerBaseClass()
574 * Initializes the service container.
576 * The cached version of the service container is used when fresh, otherwise the
577 * container is built.
579 protected function initializeContainer()
581 $class = $this->getContainerClass();
582 $cacheDir = $this->warmupDir ?: $this->getCacheDir();
583 $cache = new ConfigCache($cacheDir.'/'.$class.'.php', $this->debug);
584 $oldContainer = null;
585 if ($fresh = $cache->isFresh()) {
586 // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
587 $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
588 $fresh = $oldContainer = false;
590 if (\is_object($this->container = include $cache->getPath())) {
591 $this->container->set('kernel', $this);
592 $oldContainer = $this->container;
595 } catch (\Throwable $e) {
596 } catch (\Exception $e) {
598 error_reporting($errorLevel);
607 $collectedLogs = array();
608 $previousHandler = defined('PHPUNIT_COMPOSER_INSTALL');
609 $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
610 if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
611 return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
614 if (isset($collectedLogs[$message])) {
615 ++$collectedLogs[$message]['count'];
620 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
621 // Clean the trace by removing first frames added by the error handler itself.
622 for ($i = 0; isset($backtrace[$i]); ++$i) {
623 if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
624 $backtrace = array_slice($backtrace, 1 + $i);
629 $collectedLogs[$message] = array(
631 'message' => $message,
634 'trace' => $backtrace,
642 $container = $this->buildContainer();
643 $container->compile();
645 if ($this->debug && true !== $previousHandler) {
646 restore_error_handler();
648 file_put_contents($cacheDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
649 file_put_contents($cacheDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
653 if (null === $oldContainer) {
654 $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
656 $oldContainer = include $cache->getPath();
657 } catch (\Throwable $e) {
658 } catch (\Exception $e) {
660 error_reporting($errorLevel);
663 $oldContainer = is_object($oldContainer) ? new \ReflectionClass($oldContainer) : false;
665 $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
666 $this->container = require $cache->getPath();
667 $this->container->set('kernel', $this);
669 if ($oldContainer && get_class($this->container) !== $oldContainer->name) {
670 // Because concurrent requests might still be using them,
671 // old container files are not removed immediately,
672 // but on a next dump of the container.
673 static $legacyContainers = array();
674 $oldContainerDir = dirname($oldContainer->getFileName());
675 $legacyContainers[$oldContainerDir.'.legacy'] = true;
676 foreach (glob(dirname($oldContainerDir).DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) {
677 if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
678 (new Filesystem())->remove(substr($legacyContainer, 0, -7));
682 touch($oldContainerDir.'.legacy');
685 if ($this->container->has('cache_warmer')) {
686 $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
691 * Returns the kernel parameters.
693 * @return array An array of kernel parameters
695 protected function getKernelParameters()
698 $bundlesMetadata = array();
700 foreach ($this->bundles as $name => $bundle) {
701 $bundles[$name] = get_class($bundle);
702 $bundlesMetadata[$name] = array(
703 'parent' => $bundle->getParent(),
704 'path' => $bundle->getPath(),
705 'namespace' => $bundle->getNamespace(),
711 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
712 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
713 'kernel.environment' => $this->environment,
714 'kernel.debug' => $this->debug,
715 'kernel.name' => $this->name,
716 'kernel.cache_dir' => realpath($cacheDir = $this->warmupDir ?: $this->getCacheDir()) ?: $cacheDir,
717 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
718 'kernel.bundles' => $bundles,
719 'kernel.bundles_metadata' => $bundlesMetadata,
720 'kernel.charset' => $this->getCharset(),
721 'kernel.container_class' => $this->getContainerClass(),
723 $this->getEnvParameters(false)
728 * Gets the environment parameters.
730 * Only the parameters starting with "SYMFONY__" are considered.
732 * @return array An array of parameters
734 * @deprecated since version 3.3, to be removed in 4.0
736 protected function getEnvParameters()
738 if (0 === func_num_args() || func_get_arg(0)) {
739 @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);
742 $parameters = array();
743 foreach ($_SERVER as $key => $value) {
744 if (0 === strpos($key, 'SYMFONY__')) {
745 @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);
746 $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
754 * Builds the service container.
756 * @return ContainerBuilder The compiled service container
758 * @throws \RuntimeException
760 protected function buildContainer()
762 foreach (array('cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
764 if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
765 throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
767 } elseif (!is_writable($dir)) {
768 throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
772 $container = $this->getContainerBuilder();
773 $container->addObjectResource($this);
774 $this->prepareContainer($container);
776 if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
777 $container->merge($cont);
780 $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
781 $container->addResource(new EnvParametersResource('SYMFONY__'));
787 * Prepares the ContainerBuilder before it is compiled.
789 protected function prepareContainer(ContainerBuilder $container)
791 $extensions = array();
792 foreach ($this->bundles as $bundle) {
793 if ($extension = $bundle->getContainerExtension()) {
794 $container->registerExtension($extension);
798 $container->addObjectResource($bundle);
802 foreach ($this->bundles as $bundle) {
803 $bundle->build($container);
806 $this->build($container);
808 foreach ($container->getExtensions() as $extension) {
809 $extensions[] = $extension->getAlias();
812 // ensure these extensions are implicitly loaded
813 $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
817 * Gets a new ContainerBuilder instance used to build the service container.
819 * @return ContainerBuilder
821 protected function getContainerBuilder()
823 $container = new ContainerBuilder();
824 $container->getParameterBag()->add($this->getKernelParameters());
826 if ($this instanceof CompilerPassInterface) {
827 $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
829 if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
830 $container->setProxyInstantiator(new RuntimeInstantiator());
837 * Dumps the service container to PHP code in the cache.
839 * @param ConfigCache $cache The config cache
840 * @param ContainerBuilder $container The service container
841 * @param string $class The name of the class to generate
842 * @param string $baseClass The name of the container's base class
844 protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
846 // cache the container
847 $dumper = new PhpDumper($container);
849 if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
850 $dumper->setProxyDumper(new ProxyDumper());
853 $content = $dumper->dump(array(
855 'base_class' => $baseClass,
856 'file' => $cache->getPath(),
858 'debug' => $this->debug,
859 'inline_class_loader_parameter' => \PHP_VERSION_ID >= 70000 && !$this->loadClassCache && !class_exists(ClassCollectionLoader::class, false) ? 'container.dumper.inline_class_loader' : null,
860 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
863 $rootCode = array_pop($content);
864 $dir = dirname($cache->getPath()).'/';
865 $fs = new Filesystem();
867 foreach ($content as $file => $code) {
868 $fs->dumpFile($dir.$file, $code);
869 @chmod($dir.$file, 0666 & ~umask());
871 @unlink(dirname($dir.$file).'.legacy');
873 $cache->write($rootCode, $container->getResources());
877 * Returns a loader for the container.
879 * @return DelegatingLoader The loader
881 protected function getContainerLoader(ContainerInterface $container)
883 $locator = new FileLocator($this);
884 $resolver = new LoaderResolver(array(
885 new XmlFileLoader($container, $locator),
886 new YamlFileLoader($container, $locator),
887 new IniFileLoader($container, $locator),
888 new PhpFileLoader($container, $locator),
889 new GlobFileLoader($container, $locator),
890 new DirectoryLoader($container, $locator),
891 new ClosureLoader($container),
894 return new DelegatingLoader($resolver);
898 * Removes comments from a PHP source string.
900 * We don't use the PHP php_strip_whitespace() function
901 * as we want the content to be readable and well-formatted.
903 * @param string $source A PHP string
905 * @return string The PHP string with the comments removed
907 public static function stripComments($source)
909 if (!function_exists('token_get_all')) {
915 $tokens = token_get_all($source);
916 $ignoreSpace = false;
917 for ($i = 0; isset($tokens[$i]); ++$i) {
918 $token = $tokens[$i];
919 if (!isset($token[1]) || 'b"' === $token) {
921 } elseif (T_START_HEREDOC === $token[0]) {
922 $output .= $rawChunk.$token[1];
924 $token = $tokens[++$i];
925 $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
926 } while (T_END_HEREDOC !== $token[0]);
928 } elseif (T_WHITESPACE === $token[0]) {
930 $ignoreSpace = false;
935 // replace multiple new lines with a single newline
936 $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
937 } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
940 $rawChunk .= $token[1];
942 // The PHP-open tag already has a new-line
943 if (T_OPEN_TAG === $token[0]) {
949 $output .= $rawChunk;
951 if (\PHP_VERSION_ID >= 70000) {
952 // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
953 unset($tokens, $rawChunk);
960 public function serialize()
962 return serialize(array($this->environment, $this->debug));
965 public function unserialize($data)
967 if (\PHP_VERSION_ID >= 70000) {
968 list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
970 list($environment, $debug) = unserialize($data);
973 $this->__construct($environment, $debug);