Kernel.php 26 KB

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