Drupal investigation

Kernel.php 24KB

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