Kernel.php 26 KB

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