You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

880 lines
29 KiB

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