Kernel.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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\ClassLoader\ClassCollectionLoader;
  14. use Symfony\Component\Config\ConfigCache;
  15. use Symfony\Component\Config\Loader\DelegatingLoader;
  16. use Symfony\Component\Config\Loader\LoaderResolver;
  17. use Symfony\Component\DependencyInjection\ContainerBuilder;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  20. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  21. use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
  22. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  23. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  24. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  25. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  26. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  30. use Symfony\Component\HttpKernel\Config\EnvParametersResource;
  31. use Symfony\Component\HttpKernel\Config\FileLocator;
  32. use Symfony\Component\HttpKernel\DependencyInjection\AddClassesToCachePass;
  33. use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
  34. /**
  35. * The Kernel is the heart of the Symfony system.
  36. *
  37. * It manages an environment made of bundles.
  38. *
  39. * @author Fabien Potencier <fabien@symfony.com>
  40. */
  41. abstract class Kernel implements KernelInterface, TerminableInterface
  42. {
  43. /**
  44. * @var BundleInterface[]
  45. */
  46. protected $bundles = array();
  47. protected $bundleMap;
  48. protected $container;
  49. protected $rootDir;
  50. protected $environment;
  51. protected $debug;
  52. protected $booted = false;
  53. protected $name;
  54. protected $startTime;
  55. protected $loadClassCache;
  56. const VERSION = '2.8.51';
  57. const VERSION_ID = 20851;
  58. const MAJOR_VERSION = 2;
  59. const MINOR_VERSION = 8;
  60. const RELEASE_VERSION = 51;
  61. const EXTRA_VERSION = '';
  62. const END_OF_MAINTENANCE = '11/2018';
  63. const END_OF_LIFE = '11/2019';
  64. /**
  65. * @param string $environment The environment
  66. * @param bool $debug Whether to enable debugging or not
  67. */
  68. public function __construct($environment, $debug)
  69. {
  70. $this->environment = $environment;
  71. $this->debug = (bool) $debug;
  72. $this->rootDir = $this->getRootDir();
  73. $this->name = $this->getName();
  74. if ($this->debug) {
  75. $this->startTime = microtime(true);
  76. }
  77. $defClass = new \ReflectionMethod($this, 'init');
  78. $defClass = $defClass->getDeclaringClass()->name;
  79. if (__CLASS__ !== $defClass) {
  80. @trigger_error(sprintf('Calling the %s::init() method is deprecated since Symfony 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', $defClass), E_USER_DEPRECATED);
  81. $this->init();
  82. }
  83. }
  84. /**
  85. * @deprecated since version 2.3, to be removed in 3.0. Move your logic in the constructor instead.
  86. */
  87. public function init()
  88. {
  89. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', E_USER_DEPRECATED);
  90. }
  91. public function __clone()
  92. {
  93. if ($this->debug) {
  94. $this->startTime = microtime(true);
  95. }
  96. $this->booted = false;
  97. $this->container = null;
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function boot()
  103. {
  104. if (true === $this->booted) {
  105. return;
  106. }
  107. if ($this->loadClassCache) {
  108. $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
  109. }
  110. // init bundles
  111. $this->initializeBundles();
  112. // init container
  113. $this->initializeContainer();
  114. foreach ($this->getBundles() as $bundle) {
  115. $bundle->setContainer($this->container);
  116. $bundle->boot();
  117. }
  118. $this->booted = true;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function terminate(Request $request, Response $response)
  124. {
  125. if (false === $this->booted) {
  126. return;
  127. }
  128. if ($this->getHttpKernel() instanceof TerminableInterface) {
  129. $this->getHttpKernel()->terminate($request, $response);
  130. }
  131. }
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function shutdown()
  136. {
  137. if (false === $this->booted) {
  138. return;
  139. }
  140. $this->booted = false;
  141. foreach ($this->getBundles() as $bundle) {
  142. $bundle->shutdown();
  143. $bundle->setContainer(null);
  144. }
  145. $this->container = null;
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  151. {
  152. if (false === $this->booted) {
  153. $this->boot();
  154. }
  155. return $this->getHttpKernel()->handle($request, $type, $catch);
  156. }
  157. /**
  158. * Gets a HTTP kernel from the container.
  159. *
  160. * @return HttpKernel
  161. */
  162. protected function getHttpKernel()
  163. {
  164. return $this->container->get('http_kernel');
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function getBundles()
  170. {
  171. return $this->bundles;
  172. }
  173. /**
  174. * {@inheritdoc}
  175. *
  176. * @deprecated since version 2.6, to be removed in 3.0.
  177. */
  178. public function isClassInActiveBundle($class)
  179. {
  180. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in version 3.0.', E_USER_DEPRECATED);
  181. foreach ($this->getBundles() as $bundle) {
  182. if (0 === strpos($class, $bundle->getNamespace())) {
  183. return true;
  184. }
  185. }
  186. return false;
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. public function getBundle($name, $first = true)
  192. {
  193. if (!isset($this->bundleMap[$name])) {
  194. 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)));
  195. }
  196. if (true === $first) {
  197. return $this->bundleMap[$name][0];
  198. }
  199. return $this->bundleMap[$name];
  200. }
  201. /**
  202. * {@inheritdoc}
  203. *
  204. * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
  205. */
  206. public function locateResource($name, $dir = null, $first = true)
  207. {
  208. if ('@' !== $name[0]) {
  209. throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
  210. }
  211. if (false !== strpos($name, '..')) {
  212. throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
  213. }
  214. $bundleName = substr($name, 1);
  215. $path = '';
  216. if (false !== strpos($bundleName, '/')) {
  217. list($bundleName, $path) = explode('/', $bundleName, 2);
  218. }
  219. $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
  220. $overridePath = substr($path, 9);
  221. $resourceBundle = null;
  222. $bundles = $this->getBundle($bundleName, false);
  223. $files = array();
  224. foreach ($bundles as $bundle) {
  225. if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
  226. if (null !== $resourceBundle) {
  227. 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));
  228. }
  229. if ($first) {
  230. return $file;
  231. }
  232. $files[] = $file;
  233. }
  234. if (file_exists($file = $bundle->getPath().'/'.$path)) {
  235. if ($first && !$isResource) {
  236. return $file;
  237. }
  238. $files[] = $file;
  239. $resourceBundle = $bundle->getName();
  240. }
  241. }
  242. if (\count($files) > 0) {
  243. return $first && $isResource ? $files[0] : $files;
  244. }
  245. throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
  246. }
  247. /**
  248. * {@inheritdoc}
  249. */
  250. public function getName()
  251. {
  252. if (null === $this->name) {
  253. $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
  254. if (ctype_digit($this->name[0])) {
  255. $this->name = '_'.$this->name;
  256. }
  257. }
  258. return $this->name;
  259. }
  260. /**
  261. * {@inheritdoc}
  262. */
  263. public function getEnvironment()
  264. {
  265. return $this->environment;
  266. }
  267. /**
  268. * {@inheritdoc}
  269. */
  270. public function isDebug()
  271. {
  272. return $this->debug;
  273. }
  274. /**
  275. * {@inheritdoc}
  276. */
  277. public function getRootDir()
  278. {
  279. if (null === $this->rootDir) {
  280. $r = new \ReflectionObject($this);
  281. $this->rootDir = \dirname($r->getFileName());
  282. }
  283. return $this->rootDir;
  284. }
  285. /**
  286. * {@inheritdoc}
  287. */
  288. public function getContainer()
  289. {
  290. return $this->container;
  291. }
  292. /**
  293. * Loads the PHP class cache.
  294. *
  295. * This methods only registers the fact that you want to load the cache classes.
  296. * The cache will actually only be loaded when the Kernel is booted.
  297. *
  298. * That optimization is mainly useful when using the HttpCache class in which
  299. * case the class cache is not loaded if the Response is in the cache.
  300. *
  301. * @param string $name The cache name prefix
  302. * @param string $extension File extension of the resulting file
  303. */
  304. public function loadClassCache($name = 'classes', $extension = '.php')
  305. {
  306. $this->loadClassCache = array($name, $extension);
  307. }
  308. /**
  309. * Used internally.
  310. */
  311. public function setClassCache(array $classes)
  312. {
  313. file_put_contents($this->getCacheDir().'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
  314. }
  315. /**
  316. * {@inheritdoc}
  317. */
  318. public function getStartTime()
  319. {
  320. return $this->debug ? $this->startTime : -INF;
  321. }
  322. /**
  323. * {@inheritdoc}
  324. */
  325. public function getCacheDir()
  326. {
  327. return $this->rootDir.'/cache/'.$this->environment;
  328. }
  329. /**
  330. * {@inheritdoc}
  331. */
  332. public function getLogDir()
  333. {
  334. return $this->rootDir.'/logs';
  335. }
  336. /**
  337. * {@inheritdoc}
  338. */
  339. public function getCharset()
  340. {
  341. return 'UTF-8';
  342. }
  343. protected function doLoadClassCache($name, $extension)
  344. {
  345. if (!$this->booted && is_file($this->getCacheDir().'/classes.map')) {
  346. ClassCollectionLoader::load(include($this->getCacheDir().'/classes.map'), $this->getCacheDir(), $name, $this->debug, false, $extension);
  347. }
  348. }
  349. /**
  350. * Initializes the data structures related to the bundle management.
  351. *
  352. * - the bundles property maps a bundle name to the bundle instance,
  353. * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
  354. *
  355. * @throws \LogicException if two bundles share a common name
  356. * @throws \LogicException if a bundle tries to extend a non-registered bundle
  357. * @throws \LogicException if a bundle tries to extend itself
  358. * @throws \LogicException if two bundles extend the same ancestor
  359. */
  360. protected function initializeBundles()
  361. {
  362. // init bundles
  363. $this->bundles = array();
  364. $topMostBundles = array();
  365. $directChildren = array();
  366. foreach ($this->registerBundles() as $bundle) {
  367. $name = $bundle->getName();
  368. if (isset($this->bundles[$name])) {
  369. throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
  370. }
  371. $this->bundles[$name] = $bundle;
  372. if ($parentName = $bundle->getParent()) {
  373. if (isset($directChildren[$parentName])) {
  374. throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
  375. }
  376. if ($parentName == $name) {
  377. throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
  378. }
  379. $directChildren[$parentName] = $name;
  380. } else {
  381. $topMostBundles[$name] = $bundle;
  382. }
  383. }
  384. // look for orphans
  385. if (!empty($directChildren) && \count($diff = array_diff_key($directChildren, $this->bundles))) {
  386. $diff = array_keys($diff);
  387. throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
  388. }
  389. // inheritance
  390. $this->bundleMap = array();
  391. foreach ($topMostBundles as $name => $bundle) {
  392. $bundleMap = array($bundle);
  393. $hierarchy = array($name);
  394. while (isset($directChildren[$name])) {
  395. $name = $directChildren[$name];
  396. array_unshift($bundleMap, $this->bundles[$name]);
  397. $hierarchy[] = $name;
  398. }
  399. foreach ($hierarchy as $hierarchyBundle) {
  400. $this->bundleMap[$hierarchyBundle] = $bundleMap;
  401. array_pop($bundleMap);
  402. }
  403. }
  404. }
  405. /**
  406. * Gets the container class.
  407. *
  408. * @return string The container class
  409. */
  410. protected function getContainerClass()
  411. {
  412. return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  413. }
  414. /**
  415. * Gets the container's base class.
  416. *
  417. * All names except Container must be fully qualified.
  418. *
  419. * @return string
  420. */
  421. protected function getContainerBaseClass()
  422. {
  423. return 'Container';
  424. }
  425. /**
  426. * Initializes the service container.
  427. *
  428. * The cached version of the service container is used when fresh, otherwise the
  429. * container is built.
  430. */
  431. protected function initializeContainer()
  432. {
  433. $class = $this->getContainerClass();
  434. $cache = new ConfigCache($this->getCacheDir().'/'.$class.'.php', $this->debug);
  435. $fresh = true;
  436. if (!$cache->isFresh()) {
  437. $container = $this->buildContainer();
  438. $container->compile();
  439. $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
  440. $fresh = false;
  441. }
  442. require_once $cache->getPath();
  443. $this->container = new $class();
  444. $this->container->set('kernel', $this);
  445. if (!$fresh && $this->container->has('cache_warmer')) {
  446. $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  447. }
  448. }
  449. /**
  450. * Returns the kernel parameters.
  451. *
  452. * @return array An array of kernel parameters
  453. */
  454. protected function getKernelParameters()
  455. {
  456. $bundles = array();
  457. $bundlesMetadata = array();
  458. foreach ($this->bundles as $name => $bundle) {
  459. $bundles[$name] = \get_class($bundle);
  460. $bundlesMetadata[$name] = array(
  461. 'parent' => $bundle->getParent(),
  462. 'path' => $bundle->getPath(),
  463. 'namespace' => $bundle->getNamespace(),
  464. );
  465. }
  466. return array_merge(
  467. array(
  468. 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
  469. 'kernel.environment' => $this->environment,
  470. 'kernel.debug' => $this->debug,
  471. 'kernel.name' => $this->name,
  472. 'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
  473. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  474. 'kernel.bundles' => $bundles,
  475. 'kernel.bundles_metadata' => $bundlesMetadata,
  476. 'kernel.charset' => $this->getCharset(),
  477. 'kernel.container_class' => $this->getContainerClass(),
  478. ),
  479. $this->getEnvParameters()
  480. );
  481. }
  482. /**
  483. * Gets the environment parameters.
  484. *
  485. * Only the parameters starting with "SYMFONY__" are considered.
  486. *
  487. * @return array An array of parameters
  488. */
  489. protected function getEnvParameters()
  490. {
  491. $parameters = array();
  492. foreach ($_SERVER as $key => $value) {
  493. if (0 === strpos($key, 'SYMFONY__')) {
  494. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  495. }
  496. }
  497. return $parameters;
  498. }
  499. /**
  500. * Builds the service container.
  501. *
  502. * @return ContainerBuilder The compiled service container
  503. *
  504. * @throws \RuntimeException
  505. */
  506. protected function buildContainer()
  507. {
  508. foreach (array('cache' => $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
  509. if (!is_dir($dir)) {
  510. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  511. throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
  512. }
  513. } elseif (!is_writable($dir)) {
  514. throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
  515. }
  516. }
  517. $container = $this->getContainerBuilder();
  518. $container->addObjectResource($this);
  519. $this->prepareContainer($container);
  520. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  521. $container->merge($cont);
  522. }
  523. $container->addCompilerPass(new AddClassesToCachePass($this));
  524. $container->addResource(new EnvParametersResource('SYMFONY__'));
  525. return $container;
  526. }
  527. /**
  528. * Prepares the ContainerBuilder before it is compiled.
  529. */
  530. protected function prepareContainer(ContainerBuilder $container)
  531. {
  532. $extensions = array();
  533. foreach ($this->bundles as $bundle) {
  534. if ($extension = $bundle->getContainerExtension()) {
  535. $container->registerExtension($extension);
  536. $extensions[] = $extension->getAlias();
  537. }
  538. if ($this->debug) {
  539. $container->addObjectResource($bundle);
  540. }
  541. }
  542. foreach ($this->bundles as $bundle) {
  543. $bundle->build($container);
  544. }
  545. // ensure these extensions are implicitly loaded
  546. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  547. }
  548. /**
  549. * Gets a new ContainerBuilder instance used to build the service container.
  550. *
  551. * @return ContainerBuilder
  552. */
  553. protected function getContainerBuilder()
  554. {
  555. $container = new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
  556. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
  557. $container->setProxyInstantiator(new RuntimeInstantiator());
  558. }
  559. return $container;
  560. }
  561. /**
  562. * Dumps the service container to PHP code in the cache.
  563. *
  564. * @param ConfigCache $cache The config cache
  565. * @param ContainerBuilder $container The service container
  566. * @param string $class The name of the class to generate
  567. * @param string $baseClass The name of the container's base class
  568. */
  569. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
  570. {
  571. // cache the container
  572. $dumper = new PhpDumper($container);
  573. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
  574. $dumper->setProxyDumper(new ProxyDumper(md5($cache->getPath())));
  575. }
  576. $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass, 'file' => $cache->getPath(), 'debug' => $this->debug));
  577. $cache->write($content, $container->getResources());
  578. }
  579. /**
  580. * Returns a loader for the container.
  581. *
  582. * @return DelegatingLoader The loader
  583. */
  584. protected function getContainerLoader(ContainerInterface $container)
  585. {
  586. $locator = new FileLocator($this);
  587. $resolver = new LoaderResolver(array(
  588. new XmlFileLoader($container, $locator),
  589. new YamlFileLoader($container, $locator),
  590. new IniFileLoader($container, $locator),
  591. new PhpFileLoader($container, $locator),
  592. new DirectoryLoader($container, $locator),
  593. new ClosureLoader($container),
  594. ));
  595. return new DelegatingLoader($resolver);
  596. }
  597. /**
  598. * Removes comments from a PHP source string.
  599. *
  600. * We don't use the PHP php_strip_whitespace() function
  601. * as we want the content to be readable and well-formatted.
  602. *
  603. * @param string $source A PHP string
  604. *
  605. * @return string The PHP string with the comments removed
  606. */
  607. public static function stripComments($source)
  608. {
  609. if (!\function_exists('token_get_all')) {
  610. return $source;
  611. }
  612. $rawChunk = '';
  613. $output = '';
  614. $tokens = token_get_all($source);
  615. $ignoreSpace = false;
  616. for ($i = 0; isset($tokens[$i]); ++$i) {
  617. $token = $tokens[$i];
  618. if (!isset($token[1]) || 'b"' === $token) {
  619. $rawChunk .= $token;
  620. } elseif (T_START_HEREDOC === $token[0]) {
  621. $output .= $rawChunk.$token[1];
  622. do {
  623. $token = $tokens[++$i];
  624. $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
  625. } while (T_END_HEREDOC !== $token[0]);
  626. $rawChunk = '';
  627. } elseif (T_WHITESPACE === $token[0]) {
  628. if ($ignoreSpace) {
  629. $ignoreSpace = false;
  630. continue;
  631. }
  632. // replace multiple new lines with a single newline
  633. $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
  634. } elseif (\in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  635. $ignoreSpace = true;
  636. } else {
  637. $rawChunk .= $token[1];
  638. // The PHP-open tag already has a new-line
  639. if (T_OPEN_TAG === $token[0]) {
  640. $ignoreSpace = true;
  641. }
  642. }
  643. }
  644. $output .= $rawChunk;
  645. if (\PHP_VERSION_ID >= 70000) {
  646. // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
  647. unset($tokens, $rawChunk);
  648. gc_mem_caches();
  649. }
  650. return $output;
  651. }
  652. public function serialize()
  653. {
  654. return serialize(array($this->environment, $this->debug));
  655. }
  656. public function unserialize($data)
  657. {
  658. list($environment, $debug) = unserialize($data);
  659. $this->__construct($environment, $debug);
  660. }
  661. }