Kernel.php 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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\Compiler\CompilerPassInterface;
  14. use Symfony\Component\DependencyInjection\Compiler\PassConfig;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Component\DependencyInjection\ContainerBuilder;
  17. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  18. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  19. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  20. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  21. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  22. use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
  23. use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
  24. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  25. use Symfony\Component\Filesystem\Filesystem;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  29. use Symfony\Component\HttpKernel\Config\FileLocator;
  30. use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
  31. use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
  32. use Symfony\Component\Config\Loader\LoaderResolver;
  33. use Symfony\Component\Config\Loader\DelegatingLoader;
  34. use Symfony\Component\Config\ConfigCache;
  35. /**
  36. * The Kernel is the heart of the Symfony system.
  37. *
  38. * It manages an environment made of bundles.
  39. *
  40. * @author Fabien Potencier <fabien@symfony.com>
  41. */
  42. abstract class Kernel implements KernelInterface, RebootableInterface, TerminableInterface
  43. {
  44. /**
  45. * @var BundleInterface[]
  46. */
  47. protected $bundles = array();
  48. protected $container;
  49. protected $rootDir;
  50. protected $environment;
  51. protected $debug;
  52. protected $booted = false;
  53. protected $name;
  54. protected $startTime;
  55. private $projectDir;
  56. private $warmupDir;
  57. private $requestStackSize = 0;
  58. private $resetServices = false;
  59. const VERSION = '4.1.0';
  60. const VERSION_ID = 40100;
  61. const MAJOR_VERSION = 4;
  62. const MINOR_VERSION = 1;
  63. const RELEASE_VERSION = 0;
  64. const EXTRA_VERSION = '';
  65. const END_OF_MAINTENANCE = '01/2019';
  66. const END_OF_LIFE = '07/2019';
  67. public function __construct(string $environment, bool $debug)
  68. {
  69. $this->environment = $environment;
  70. $this->debug = $debug;
  71. $this->rootDir = $this->getRootDir();
  72. $this->name = $this->getName();
  73. }
  74. public function __clone()
  75. {
  76. $this->booted = false;
  77. $this->container = null;
  78. $this->requestStackSize = 0;
  79. $this->resetServices = false;
  80. }
  81. /**
  82. * Boots the current kernel.
  83. */
  84. public function boot()
  85. {
  86. if (true === $this->booted) {
  87. if (!$this->requestStackSize && $this->resetServices) {
  88. if ($this->container->has('services_resetter')) {
  89. $this->container->get('services_resetter')->reset();
  90. }
  91. $this->resetServices = false;
  92. if ($this->debug) {
  93. $this->startTime = microtime(true);
  94. }
  95. }
  96. return;
  97. }
  98. if ($this->debug) {
  99. $this->startTime = microtime(true);
  100. }
  101. if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
  102. putenv('SHELL_VERBOSITY=3');
  103. $_ENV['SHELL_VERBOSITY'] = 3;
  104. $_SERVER['SHELL_VERBOSITY'] = 3;
  105. }
  106. // init bundles
  107. $this->initializeBundles();
  108. // init container
  109. $this->initializeContainer();
  110. foreach ($this->getBundles() as $bundle) {
  111. $bundle->setContainer($this->container);
  112. $bundle->boot();
  113. }
  114. $this->booted = true;
  115. }
  116. /**
  117. * {@inheritdoc}
  118. */
  119. public function reboot($warmupDir)
  120. {
  121. $this->shutdown();
  122. $this->warmupDir = $warmupDir;
  123. $this->boot();
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function terminate(Request $request, Response $response)
  129. {
  130. if (false === $this->booted) {
  131. return;
  132. }
  133. if ($this->getHttpKernel() instanceof TerminableInterface) {
  134. $this->getHttpKernel()->terminate($request, $response);
  135. }
  136. }
  137. /**
  138. * {@inheritdoc}
  139. */
  140. public function shutdown()
  141. {
  142. if (false === $this->booted) {
  143. return;
  144. }
  145. $this->booted = false;
  146. foreach ($this->getBundles() as $bundle) {
  147. $bundle->shutdown();
  148. $bundle->setContainer(null);
  149. }
  150. $this->container = null;
  151. $this->requestStackSize = 0;
  152. $this->resetServices = false;
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  158. {
  159. $this->boot();
  160. ++$this->requestStackSize;
  161. $this->resetServices = true;
  162. try {
  163. return $this->getHttpKernel()->handle($request, $type, $catch);
  164. } finally {
  165. --$this->requestStackSize;
  166. }
  167. }
  168. /**
  169. * Gets a HTTP kernel from the container.
  170. *
  171. * @return HttpKernel
  172. */
  173. protected function getHttpKernel()
  174. {
  175. return $this->container->get('http_kernel');
  176. }
  177. /**
  178. * {@inheritdoc}
  179. */
  180. public function getBundles()
  181. {
  182. return $this->bundles;
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. public function getBundle($name)
  188. {
  189. if (!isset($this->bundles[$name])) {
  190. 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)));
  191. }
  192. return $this->bundles[$name];
  193. }
  194. /**
  195. * {@inheritdoc}
  196. *
  197. * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
  198. */
  199. public function locateResource($name, $dir = null, $first = true)
  200. {
  201. if ('@' !== $name[0]) {
  202. throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
  203. }
  204. if (false !== strpos($name, '..')) {
  205. throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
  206. }
  207. $bundleName = substr($name, 1);
  208. $path = '';
  209. if (false !== strpos($bundleName, '/')) {
  210. list($bundleName, $path) = explode('/', $bundleName, 2);
  211. }
  212. $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
  213. $overridePath = substr($path, 9);
  214. $resourceBundle = null;
  215. $bundle = $this->getBundle($bundleName);
  216. $files = array();
  217. if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
  218. if (null !== $resourceBundle) {
  219. 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.',
  220. $file,
  221. $resourceBundle,
  222. $dir.'/'.$bundle->getName().$overridePath
  223. ));
  224. }
  225. $files[] = $file;
  226. }
  227. if (file_exists($file = $bundle->getPath().'/'.$path)) {
  228. if ($first && !$isResource) {
  229. return $file;
  230. }
  231. $files[] = $file;
  232. $resourceBundle = $bundle->getName();
  233. }
  234. if (count($files) > 0) {
  235. return $first && $isResource ? $files[0] : $files;
  236. }
  237. throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
  238. }
  239. /**
  240. * {@inheritdoc}
  241. */
  242. public function getName()
  243. {
  244. if (null === $this->name) {
  245. $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
  246. if (ctype_digit($this->name[0])) {
  247. $this->name = '_'.$this->name;
  248. }
  249. }
  250. return $this->name;
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. public function getEnvironment()
  256. {
  257. return $this->environment;
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function isDebug()
  263. {
  264. return $this->debug;
  265. }
  266. /**
  267. * {@inheritdoc}
  268. */
  269. public function getRootDir()
  270. {
  271. if (null === $this->rootDir) {
  272. $r = new \ReflectionObject($this);
  273. $this->rootDir = dirname($r->getFileName());
  274. }
  275. return $this->rootDir;
  276. }
  277. /**
  278. * Gets the application root dir (path of the project's composer file).
  279. *
  280. * @return string The project root dir
  281. */
  282. public function getProjectDir()
  283. {
  284. if (null === $this->projectDir) {
  285. $r = new \ReflectionObject($this);
  286. $dir = $rootDir = dirname($r->getFileName());
  287. while (!file_exists($dir.'/composer.json')) {
  288. if ($dir === dirname($dir)) {
  289. return $this->projectDir = $rootDir;
  290. }
  291. $dir = dirname($dir);
  292. }
  293. $this->projectDir = $dir;
  294. }
  295. return $this->projectDir;
  296. }
  297. /**
  298. * {@inheritdoc}
  299. */
  300. public function getContainer()
  301. {
  302. return $this->container;
  303. }
  304. /**
  305. * @internal
  306. */
  307. public function setAnnotatedClassCache(array $annotatedClasses)
  308. {
  309. file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/annotations.map', sprintf('<?php return %s;', var_export($annotatedClasses, true)));
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. public function getStartTime()
  315. {
  316. return $this->debug ? $this->startTime : -INF;
  317. }
  318. /**
  319. * {@inheritdoc}
  320. */
  321. public function getCacheDir()
  322. {
  323. return $this->rootDir.'/cache/'.$this->environment;
  324. }
  325. /**
  326. * {@inheritdoc}
  327. */
  328. public function getLogDir()
  329. {
  330. return $this->rootDir.'/logs';
  331. }
  332. /**
  333. * {@inheritdoc}
  334. */
  335. public function getCharset()
  336. {
  337. return 'UTF-8';
  338. }
  339. /**
  340. * Gets the patterns defining the classes to parse and cache for annotations.
  341. */
  342. public function getAnnotatedClassesToCompile(): array
  343. {
  344. return array();
  345. }
  346. /**
  347. * Initializes bundles.
  348. *
  349. * @throws \LogicException if two bundles share a common name
  350. */
  351. protected function initializeBundles()
  352. {
  353. // init bundles
  354. $this->bundles = array();
  355. foreach ($this->registerBundles() as $bundle) {
  356. $name = $bundle->getName();
  357. if (isset($this->bundles[$name])) {
  358. throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
  359. }
  360. $this->bundles[$name] = $bundle;
  361. }
  362. }
  363. /**
  364. * The extension point similar to the Bundle::build() method.
  365. *
  366. * Use this method to register compiler passes and manipulate the container during the building process.
  367. */
  368. protected function build(ContainerBuilder $container)
  369. {
  370. }
  371. /**
  372. * Gets the container class.
  373. *
  374. * @return string The container class
  375. */
  376. protected function getContainerClass()
  377. {
  378. return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  379. }
  380. /**
  381. * Gets the container's base class.
  382. *
  383. * All names except Container must be fully qualified.
  384. *
  385. * @return string
  386. */
  387. protected function getContainerBaseClass()
  388. {
  389. return 'Container';
  390. }
  391. /**
  392. * Initializes the service container.
  393. *
  394. * The cached version of the service container is used when fresh, otherwise the
  395. * container is built.
  396. */
  397. protected function initializeContainer()
  398. {
  399. $class = $this->getContainerClass();
  400. $cacheDir = $this->warmupDir ?: $this->getCacheDir();
  401. $cache = new ConfigCache($cacheDir.'/'.$class.'.php', $this->debug);
  402. $oldContainer = null;
  403. if ($fresh = $cache->isFresh()) {
  404. // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
  405. $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
  406. $fresh = $oldContainer = false;
  407. try {
  408. if (file_exists($cache->getPath()) && \is_object($this->container = include $cache->getPath())) {
  409. $this->container->set('kernel', $this);
  410. $oldContainer = $this->container;
  411. $fresh = true;
  412. }
  413. } catch (\Throwable $e) {
  414. } catch (\Exception $e) {
  415. } finally {
  416. error_reporting($errorLevel);
  417. }
  418. }
  419. if ($fresh) {
  420. return;
  421. }
  422. if ($this->debug) {
  423. $collectedLogs = array();
  424. $previousHandler = defined('PHPUNIT_COMPOSER_INSTALL');
  425. $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
  426. if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
  427. return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
  428. }
  429. if (isset($collectedLogs[$message])) {
  430. ++$collectedLogs[$message]['count'];
  431. return;
  432. }
  433. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  434. // Clean the trace by removing first frames added by the error handler itself.
  435. for ($i = 0; isset($backtrace[$i]); ++$i) {
  436. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  437. $backtrace = array_slice($backtrace, 1 + $i);
  438. break;
  439. }
  440. }
  441. $collectedLogs[$message] = array(
  442. 'type' => $type,
  443. 'message' => $message,
  444. 'file' => $file,
  445. 'line' => $line,
  446. 'trace' => $backtrace,
  447. 'count' => 1,
  448. );
  449. });
  450. }
  451. try {
  452. $container = null;
  453. $container = $this->buildContainer();
  454. $container->compile();
  455. } finally {
  456. if ($this->debug && true !== $previousHandler) {
  457. restore_error_handler();
  458. file_put_contents($cacheDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
  459. file_put_contents($cacheDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
  460. }
  461. }
  462. if (null === $oldContainer && file_exists($cache->getPath())) {
  463. $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
  464. try {
  465. $oldContainer = include $cache->getPath();
  466. } catch (\Throwable $e) {
  467. } catch (\Exception $e) {
  468. } finally {
  469. error_reporting($errorLevel);
  470. }
  471. }
  472. $oldContainer = is_object($oldContainer) ? new \ReflectionClass($oldContainer) : false;
  473. $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
  474. $this->container = require $cache->getPath();
  475. $this->container->set('kernel', $this);
  476. if ($oldContainer && get_class($this->container) !== $oldContainer->name) {
  477. // Because concurrent requests might still be using them,
  478. // old container files are not removed immediately,
  479. // but on a next dump of the container.
  480. static $legacyContainers = array();
  481. $oldContainerDir = dirname($oldContainer->getFileName());
  482. $legacyContainers[$oldContainerDir.'.legacy'] = true;
  483. foreach (glob(dirname($oldContainerDir).DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) {
  484. if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
  485. (new Filesystem())->remove(substr($legacyContainer, 0, -7));
  486. }
  487. }
  488. touch($oldContainerDir.'.legacy');
  489. }
  490. if ($this->container->has('cache_warmer')) {
  491. $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  492. }
  493. }
  494. /**
  495. * Returns the kernel parameters.
  496. *
  497. * @return array An array of kernel parameters
  498. */
  499. protected function getKernelParameters()
  500. {
  501. $bundles = array();
  502. $bundlesMetadata = array();
  503. foreach ($this->bundles as $name => $bundle) {
  504. $bundles[$name] = get_class($bundle);
  505. $bundlesMetadata[$name] = array(
  506. 'path' => $bundle->getPath(),
  507. 'namespace' => $bundle->getNamespace(),
  508. );
  509. }
  510. return array(
  511. 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
  512. 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  513. 'kernel.environment' => $this->environment,
  514. 'kernel.debug' => $this->debug,
  515. 'kernel.name' => $this->name,
  516. 'kernel.cache_dir' => realpath($cacheDir = $this->warmupDir ?: $this->getCacheDir()) ?: $cacheDir,
  517. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  518. 'kernel.bundles' => $bundles,
  519. 'kernel.bundles_metadata' => $bundlesMetadata,
  520. 'kernel.charset' => $this->getCharset(),
  521. 'kernel.container_class' => $this->getContainerClass(),
  522. );
  523. }
  524. /**
  525. * Builds the service container.
  526. *
  527. * @return ContainerBuilder The compiled service container
  528. *
  529. * @throws \RuntimeException
  530. */
  531. protected function buildContainer()
  532. {
  533. foreach (array('cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
  534. if (!is_dir($dir)) {
  535. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  536. throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
  537. }
  538. } elseif (!is_writable($dir)) {
  539. throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
  540. }
  541. }
  542. $container = $this->getContainerBuilder();
  543. $container->addObjectResource($this);
  544. $this->prepareContainer($container);
  545. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  546. $container->merge($cont);
  547. }
  548. $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
  549. return $container;
  550. }
  551. /**
  552. * Prepares the ContainerBuilder before it is compiled.
  553. */
  554. protected function prepareContainer(ContainerBuilder $container)
  555. {
  556. $extensions = array();
  557. foreach ($this->bundles as $bundle) {
  558. if ($extension = $bundle->getContainerExtension()) {
  559. $container->registerExtension($extension);
  560. }
  561. if ($this->debug) {
  562. $container->addObjectResource($bundle);
  563. }
  564. }
  565. foreach ($this->bundles as $bundle) {
  566. $bundle->build($container);
  567. }
  568. $this->build($container);
  569. foreach ($container->getExtensions() as $extension) {
  570. $extensions[] = $extension->getAlias();
  571. }
  572. // ensure these extensions are implicitly loaded
  573. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  574. }
  575. /**
  576. * Gets a new ContainerBuilder instance used to build the service container.
  577. *
  578. * @return ContainerBuilder
  579. */
  580. protected function getContainerBuilder()
  581. {
  582. $container = new ContainerBuilder();
  583. $container->getParameterBag()->add($this->getKernelParameters());
  584. if ($this instanceof CompilerPassInterface) {
  585. $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
  586. }
  587. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
  588. $container->setProxyInstantiator(new RuntimeInstantiator());
  589. }
  590. return $container;
  591. }
  592. /**
  593. * Dumps the service container to PHP code in the cache.
  594. *
  595. * @param ConfigCache $cache The config cache
  596. * @param ContainerBuilder $container The service container
  597. * @param string $class The name of the class to generate
  598. * @param string $baseClass The name of the container's base class
  599. */
  600. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
  601. {
  602. // cache the container
  603. $dumper = new PhpDumper($container);
  604. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
  605. $dumper->setProxyDumper(new ProxyDumper());
  606. }
  607. $content = $dumper->dump(array(
  608. 'class' => $class,
  609. 'base_class' => $baseClass,
  610. 'file' => $cache->getPath(),
  611. 'as_files' => true,
  612. 'debug' => $this->debug,
  613. 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
  614. ));
  615. $rootCode = array_pop($content);
  616. $dir = dirname($cache->getPath()).'/';
  617. $fs = new Filesystem();
  618. foreach ($content as $file => $code) {
  619. $fs->dumpFile($dir.$file, $code);
  620. @chmod($dir.$file, 0666 & ~umask());
  621. }
  622. @unlink(dirname($dir.$file).'.legacy');
  623. $cache->write($rootCode, $container->getResources());
  624. }
  625. /**
  626. * Returns a loader for the container.
  627. *
  628. * @return DelegatingLoader The loader
  629. */
  630. protected function getContainerLoader(ContainerInterface $container)
  631. {
  632. $locator = new FileLocator($this);
  633. $resolver = new LoaderResolver(array(
  634. new XmlFileLoader($container, $locator),
  635. new YamlFileLoader($container, $locator),
  636. new IniFileLoader($container, $locator),
  637. new PhpFileLoader($container, $locator),
  638. new GlobFileLoader($container, $locator),
  639. new DirectoryLoader($container, $locator),
  640. new ClosureLoader($container),
  641. ));
  642. return new DelegatingLoader($resolver);
  643. }
  644. /**
  645. * Removes comments from a PHP source string.
  646. *
  647. * We don't use the PHP php_strip_whitespace() function
  648. * as we want the content to be readable and well-formatted.
  649. *
  650. * @param string $source A PHP string
  651. *
  652. * @return string The PHP string with the comments removed
  653. */
  654. public static function stripComments($source)
  655. {
  656. if (!function_exists('token_get_all')) {
  657. return $source;
  658. }
  659. $rawChunk = '';
  660. $output = '';
  661. $tokens = token_get_all($source);
  662. $ignoreSpace = false;
  663. for ($i = 0; isset($tokens[$i]); ++$i) {
  664. $token = $tokens[$i];
  665. if (!isset($token[1]) || 'b"' === $token) {
  666. $rawChunk .= $token;
  667. } elseif (T_START_HEREDOC === $token[0]) {
  668. $output .= $rawChunk.$token[1];
  669. do {
  670. $token = $tokens[++$i];
  671. $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
  672. } while (T_END_HEREDOC !== $token[0]);
  673. $rawChunk = '';
  674. } elseif (T_WHITESPACE === $token[0]) {
  675. if ($ignoreSpace) {
  676. $ignoreSpace = false;
  677. continue;
  678. }
  679. // replace multiple new lines with a single newline
  680. $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
  681. } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  682. $ignoreSpace = true;
  683. } else {
  684. $rawChunk .= $token[1];
  685. // The PHP-open tag already has a new-line
  686. if (T_OPEN_TAG === $token[0]) {
  687. $ignoreSpace = true;
  688. }
  689. }
  690. }
  691. $output .= $rawChunk;
  692. // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
  693. unset($tokens, $rawChunk);
  694. gc_mem_caches();
  695. return $output;
  696. }
  697. public function serialize()
  698. {
  699. return serialize(array($this->environment, $this->debug));
  700. }
  701. public function unserialize($data)
  702. {
  703. list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
  704. $this->__construct($environment, $debug);
  705. }
  706. }