Kernel.php 32 KB

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