Kernel.php 28 KB

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