vendor/symfony/http-kernel/Kernel.php line 767

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