Kernel.php 28 KB

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