菜谱项目

Kernel.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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\DependencyInjection\ContainerInterface;
  14. use Symfony\Component\DependencyInjection\ContainerBuilder;
  15. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  16. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  17. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  18. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  19. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  20. use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
  21. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  25. use Symfony\Component\HttpKernel\Config\EnvParametersResource;
  26. use Symfony\Component\HttpKernel\Config\FileLocator;
  27. use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
  28. use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
  29. use Symfony\Component\Config\Loader\GlobFileLoader;
  30. use Symfony\Component\Config\Loader\LoaderResolver;
  31. use Symfony\Component\Config\Loader\DelegatingLoader;
  32. use Symfony\Component\Config\ConfigCache;
  33. use Symfony\Component\ClassLoader\ClassCollectionLoader;
  34. /**
  35. * The Kernel is the heart of the Symfony system.
  36. *
  37. * It manages an environment made of bundles.
  38. *
  39. * @author Fabien Potencier <fabien@symfony.com>
  40. */
  41. abstract class Kernel implements KernelInterface, TerminableInterface
  42. {
  43. /**
  44. * @var BundleInterface[]
  45. */
  46. protected $bundles = array();
  47. protected $bundleMap;
  48. protected $container;
  49. protected $rootDir;
  50. protected $environment;
  51. protected $debug;
  52. protected $booted = false;
  53. protected $name;
  54. protected $startTime;
  55. protected $loadClassCache;
  56. private $projectDir;
  57. const VERSION = '3.3.11';
  58. const VERSION_ID = 30311;
  59. const MAJOR_VERSION = 3;
  60. const MINOR_VERSION = 3;
  61. const RELEASE_VERSION = 11;
  62. const EXTRA_VERSION = '';
  63. const END_OF_MAINTENANCE = '01/2018';
  64. const END_OF_LIFE = '07/2018';
  65. /**
  66. * @param string $environment The environment
  67. * @param bool $debug Whether to enable debugging or not
  68. */
  69. public function __construct($environment, $debug)
  70. {
  71. $this->environment = $environment;
  72. $this->debug = (bool) $debug;
  73. $this->rootDir = $this->getRootDir();
  74. $this->name = $this->getName();
  75. if ($this->debug) {
  76. $this->startTime = microtime(true);
  77. }
  78. }
  79. public function __clone()
  80. {
  81. if ($this->debug) {
  82. $this->startTime = microtime(true);
  83. }
  84. $this->booted = false;
  85. $this->container = null;
  86. }
  87. /**
  88. * Boots the current kernel.
  89. */
  90. public function boot()
  91. {
  92. if (true === $this->booted) {
  93. return;
  94. }
  95. if ($this->loadClassCache) {
  96. $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
  97. }
  98. // init bundles
  99. $this->initializeBundles();
  100. // init container
  101. $this->initializeContainer();
  102. foreach ($this->getBundles() as $bundle) {
  103. $bundle->setContainer($this->container);
  104. $bundle->boot();
  105. }
  106. $this->booted = true;
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. public function terminate(Request $request, Response $response)
  112. {
  113. if (false === $this->booted) {
  114. return;
  115. }
  116. if ($this->getHttpKernel() instanceof TerminableInterface) {
  117. $this->getHttpKernel()->terminate($request, $response);
  118. }
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function shutdown()
  124. {
  125. if (false === $this->booted) {
  126. return;
  127. }
  128. $this->booted = false;
  129. foreach ($this->getBundles() as $bundle) {
  130. $bundle->shutdown();
  131. $bundle->setContainer(null);
  132. }
  133. $this->container = null;
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  139. {
  140. if (false === $this->booted) {
  141. $this->boot();
  142. }
  143. return $this->getHttpKernel()->handle($request, $type, $catch);
  144. }
  145. /**
  146. * Gets a HTTP kernel from the container.
  147. *
  148. * @return HttpKernel
  149. */
  150. protected function getHttpKernel()
  151. {
  152. return $this->container->get('http_kernel');
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. public function getBundles()
  158. {
  159. return $this->bundles;
  160. }
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function getBundle($name, $first = true)
  165. {
  166. if (!isset($this->bundleMap[$name])) {
  167. 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_class($this)));
  168. }
  169. if (true === $first) {
  170. return $this->bundleMap[$name][0];
  171. }
  172. return $this->bundleMap[$name];
  173. }
  174. /**
  175. * {@inheritdoc}
  176. *
  177. * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
  178. */
  179. public function locateResource($name, $dir = null, $first = true)
  180. {
  181. if ('@' !== $name[0]) {
  182. throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
  183. }
  184. if (false !== strpos($name, '..')) {
  185. throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
  186. }
  187. $bundleName = substr($name, 1);
  188. $path = '';
  189. if (false !== strpos($bundleName, '/')) {
  190. list($bundleName, $path) = explode('/', $bundleName, 2);
  191. }
  192. $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
  193. $overridePath = substr($path, 9);
  194. $resourceBundle = null;
  195. $bundles = $this->getBundle($bundleName, false);
  196. $files = array();
  197. foreach ($bundles as $bundle) {
  198. if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
  199. if (null !== $resourceBundle) {
  200. throw new \RuntimeException(sprintf('"%s" resource is hidden by a resource from the "%s" derived bundle. Create a "%s" file to override the bundle resource.',
  201. $file,
  202. $resourceBundle,
  203. $dir.'/'.$bundles[0]->getName().$overridePath
  204. ));
  205. }
  206. if ($first) {
  207. return $file;
  208. }
  209. $files[] = $file;
  210. }
  211. if (file_exists($file = $bundle->getPath().'/'.$path)) {
  212. if ($first && !$isResource) {
  213. return $file;
  214. }
  215. $files[] = $file;
  216. $resourceBundle = $bundle->getName();
  217. }
  218. }
  219. if (count($files) > 0) {
  220. return $first && $isResource ? $files[0] : $files;
  221. }
  222. throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function getName()
  228. {
  229. if (null === $this->name) {
  230. $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
  231. if (ctype_digit($this->name[0])) {
  232. $this->name = '_'.$this->name;
  233. }
  234. }
  235. return $this->name;
  236. }
  237. /**
  238. * {@inheritdoc}
  239. */
  240. public function getEnvironment()
  241. {
  242. return $this->environment;
  243. }
  244. /**
  245. * {@inheritdoc}
  246. */
  247. public function isDebug()
  248. {
  249. return $this->debug;
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function getRootDir()
  255. {
  256. if (null === $this->rootDir) {
  257. $r = new \ReflectionObject($this);
  258. $this->rootDir = dirname($r->getFileName());
  259. }
  260. return $this->rootDir;
  261. }
  262. /**
  263. * Gets the application root dir (path of the project's composer file).
  264. *
  265. * @return string The project root dir
  266. */
  267. public function getProjectDir()
  268. {
  269. if (null === $this->projectDir) {
  270. $r = new \ReflectionObject($this);
  271. $dir = $rootDir = dirname($r->getFileName());
  272. while (!file_exists($dir.'/composer.json')) {
  273. if ($dir === dirname($dir)) {
  274. return $this->projectDir = $rootDir;
  275. }
  276. $dir = dirname($dir);
  277. }
  278. $this->projectDir = $dir;
  279. }
  280. return $this->projectDir;
  281. }
  282. /**
  283. * {@inheritdoc}
  284. */
  285. public function getContainer()
  286. {
  287. return $this->container;
  288. }
  289. /**
  290. * Loads the PHP class cache.
  291. *
  292. * This methods only registers the fact that you want to load the cache classes.
  293. * The cache will actually only be loaded when the Kernel is booted.
  294. *
  295. * That optimization is mainly useful when using the HttpCache class in which
  296. * case the class cache is not loaded if the Response is in the cache.
  297. *
  298. * @param string $name The cache name prefix
  299. * @param string $extension File extension of the resulting file
  300. *
  301. * @deprecated since version 3.3, to be removed in 4.0. The class cache is not needed anymore when using PHP 7.0.
  302. */
  303. public function loadClassCache($name = 'classes', $extension = '.php')
  304. {
  305. if (\PHP_VERSION_ID >= 70000) {
  306. @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
  307. }
  308. $this->loadClassCache = array($name, $extension);
  309. }
  310. /**
  311. * @internal
  312. *
  313. * @deprecated since version 3.3, to be removed in 4.0.
  314. */
  315. public function setClassCache(array $classes)
  316. {
  317. if (\PHP_VERSION_ID >= 70000) {
  318. @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
  319. }
  320. file_put_contents($this->getCacheDir().'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
  321. }
  322. /**
  323. * @internal
  324. */
  325. public function setAnnotatedClassCache(array $annotatedClasses)
  326. {
  327. file_put_contents($this->getCacheDir().'/annotations.map', sprintf('<?php return %s;', var_export($annotatedClasses, true)));
  328. }
  329. /**
  330. * {@inheritdoc}
  331. */
  332. public function getStartTime()
  333. {
  334. return $this->debug ? $this->startTime : -INF;
  335. }
  336. /**
  337. * {@inheritdoc}
  338. */
  339. public function getCacheDir()
  340. {
  341. return $this->rootDir.'/cache/'.$this->environment;
  342. }
  343. /**
  344. * {@inheritdoc}
  345. */
  346. public function getLogDir()
  347. {
  348. return $this->rootDir.'/logs';
  349. }
  350. /**
  351. * {@inheritdoc}
  352. */
  353. public function getCharset()
  354. {
  355. return 'UTF-8';
  356. }
  357. /**
  358. * @deprecated since version 3.3, to be removed in 4.0.
  359. */
  360. protected function doLoadClassCache($name, $extension)
  361. {
  362. if (\PHP_VERSION_ID >= 70000) {
  363. @trigger_error(__METHOD__.'() is deprecated since version 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
  364. }
  365. if (!$this->booted && is_file($this->getCacheDir().'/classes.map')) {
  366. ClassCollectionLoader::load(include($this->getCacheDir().'/classes.map'), $this->getCacheDir(), $name, $this->debug, false, $extension);
  367. }
  368. }
  369. /**
  370. * Initializes the data structures related to the bundle management.
  371. *
  372. * - the bundles property maps a bundle name to the bundle instance,
  373. * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
  374. *
  375. * @throws \LogicException if two bundles share a common name
  376. * @throws \LogicException if a bundle tries to extend a non-registered bundle
  377. * @throws \LogicException if a bundle tries to extend itself
  378. * @throws \LogicException if two bundles extend the same ancestor
  379. */
  380. protected function initializeBundles()
  381. {
  382. // init bundles
  383. $this->bundles = array();
  384. $topMostBundles = array();
  385. $directChildren = array();
  386. foreach ($this->registerBundles() as $bundle) {
  387. $name = $bundle->getName();
  388. if (isset($this->bundles[$name])) {
  389. throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
  390. }
  391. $this->bundles[$name] = $bundle;
  392. if ($parentName = $bundle->getParent()) {
  393. if (isset($directChildren[$parentName])) {
  394. throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
  395. }
  396. if ($parentName == $name) {
  397. throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
  398. }
  399. $directChildren[$parentName] = $name;
  400. } else {
  401. $topMostBundles[$name] = $bundle;
  402. }
  403. }
  404. // look for orphans
  405. if (!empty($directChildren) && count($diff = array_diff_key($directChildren, $this->bundles))) {
  406. $diff = array_keys($diff);
  407. throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
  408. }
  409. // inheritance
  410. $this->bundleMap = array();
  411. foreach ($topMostBundles as $name => $bundle) {
  412. $bundleMap = array($bundle);
  413. $hierarchy = array($name);
  414. while (isset($directChildren[$name])) {
  415. $name = $directChildren[$name];
  416. array_unshift($bundleMap, $this->bundles[$name]);
  417. $hierarchy[] = $name;
  418. }
  419. foreach ($hierarchy as $hierarchyBundle) {
  420. $this->bundleMap[$hierarchyBundle] = $bundleMap;
  421. array_pop($bundleMap);
  422. }
  423. }
  424. }
  425. /**
  426. * The extension point similar to the Bundle::build() method.
  427. *
  428. * Use this method to register compiler passes and manipulate the container during the building process.
  429. */
  430. protected function build(ContainerBuilder $container)
  431. {
  432. }
  433. /**
  434. * Gets the container class.
  435. *
  436. * @return string The container class
  437. */
  438. protected function getContainerClass()
  439. {
  440. return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  441. }
  442. /**
  443. * Gets the container's base class.
  444. *
  445. * All names except Container must be fully qualified.
  446. *
  447. * @return string
  448. */
  449. protected function getContainerBaseClass()
  450. {
  451. return 'Container';
  452. }
  453. /**
  454. * Initializes the service container.
  455. *
  456. * The cached version of the service container is used when fresh, otherwise the
  457. * container is built.
  458. */
  459. protected function initializeContainer()
  460. {
  461. $class = $this->getContainerClass();
  462. $cache = new ConfigCache($this->getCacheDir().'/'.$class.'.php', $this->debug);
  463. $fresh = true;
  464. if (!$cache->isFresh()) {
  465. if ($this->debug) {
  466. $collectedLogs = array();
  467. $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
  468. if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
  469. return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
  470. }
  471. if (isset($collectedLogs[$message])) {
  472. ++$collectedLogs[$message]['count'];
  473. return;
  474. }
  475. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  476. // Clean the trace by removing first frames added by the error handler itself.
  477. for ($i = 0; isset($backtrace[$i]); ++$i) {
  478. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  479. $backtrace = array_slice($backtrace, 1 + $i);
  480. break;
  481. }
  482. }
  483. $collectedLogs[$message] = array(
  484. 'type' => $type,
  485. 'message' => $message,
  486. 'file' => $file,
  487. 'line' => $line,
  488. 'trace' => $backtrace,
  489. 'count' => 1,
  490. );
  491. });
  492. }
  493. try {
  494. $container = null;
  495. $container = $this->buildContainer();
  496. $container->compile();
  497. } finally {
  498. if ($this->debug) {
  499. restore_error_handler();
  500. file_put_contents($this->getCacheDir().'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
  501. file_put_contents($this->getCacheDir().'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
  502. }
  503. }
  504. $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
  505. $fresh = false;
  506. }
  507. require_once $cache->getPath();
  508. $this->container = new $class();
  509. $this->container->set('kernel', $this);
  510. if (!$fresh && $this->container->has('cache_warmer')) {
  511. $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  512. }
  513. }
  514. /**
  515. * Returns the kernel parameters.
  516. *
  517. * @return array An array of kernel parameters
  518. */
  519. protected function getKernelParameters()
  520. {
  521. $bundles = array();
  522. $bundlesMetadata = array();
  523. foreach ($this->bundles as $name => $bundle) {
  524. $bundles[$name] = get_class($bundle);
  525. $bundlesMetadata[$name] = array(
  526. 'parent' => $bundle->getParent(),
  527. 'path' => $bundle->getPath(),
  528. 'namespace' => $bundle->getNamespace(),
  529. );
  530. }
  531. return array_merge(
  532. array(
  533. 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
  534. 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  535. 'kernel.environment' => $this->environment,
  536. 'kernel.debug' => $this->debug,
  537. 'kernel.name' => $this->name,
  538. 'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
  539. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  540. 'kernel.bundles' => $bundles,
  541. 'kernel.bundles_metadata' => $bundlesMetadata,
  542. 'kernel.charset' => $this->getCharset(),
  543. 'kernel.container_class' => $this->getContainerClass(),
  544. ),
  545. $this->getEnvParameters(false)
  546. );
  547. }
  548. /**
  549. * Gets the environment parameters.
  550. *
  551. * Only the parameters starting with "SYMFONY__" are considered.
  552. *
  553. * @return array An array of parameters
  554. *
  555. * @deprecated since version 3.3, to be removed in 4.0
  556. */
  557. protected function getEnvParameters()
  558. {
  559. if (0 === func_num_args() || func_get_arg(0)) {
  560. @trigger_error(sprintf('The %s() method is deprecated as of 3.3 and will be removed in 4.0. Use the %%env()%% syntax to get the value of any environment variable from configuration files instead.', __METHOD__), E_USER_DEPRECATED);
  561. }
  562. $parameters = array();
  563. foreach ($_SERVER as $key => $value) {
  564. if (0 === strpos($key, 'SYMFONY__')) {
  565. @trigger_error(sprintf('The support of special environment variables that start with SYMFONY__ (such as "%s") is deprecated as of 3.3 and will be removed in 4.0. Use the %%env()%% syntax instead to get the value of environment variables in configuration files.', $key), E_USER_DEPRECATED);
  566. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  567. }
  568. }
  569. return $parameters;
  570. }
  571. /**
  572. * Builds the service container.
  573. *
  574. * @return ContainerBuilder The compiled service container
  575. *
  576. * @throws \RuntimeException
  577. */
  578. protected function buildContainer()
  579. {
  580. foreach (array('cache' => $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
  581. if (!is_dir($dir)) {
  582. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  583. throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
  584. }
  585. } elseif (!is_writable($dir)) {
  586. throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
  587. }
  588. }
  589. $container = $this->getContainerBuilder();
  590. $container->addObjectResource($this);
  591. $this->prepareContainer($container);
  592. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  593. $container->merge($cont);
  594. }
  595. $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
  596. $container->addResource(new EnvParametersResource('SYMFONY__'));
  597. return $container;
  598. }
  599. /**
  600. * Prepares the ContainerBuilder before it is compiled.
  601. */
  602. protected function prepareContainer(ContainerBuilder $container)
  603. {
  604. $extensions = array();
  605. foreach ($this->bundles as $bundle) {
  606. if ($extension = $bundle->getContainerExtension()) {
  607. $container->registerExtension($extension);
  608. $extensions[] = $extension->getAlias();
  609. }
  610. if ($this->debug) {
  611. $container->addObjectResource($bundle);
  612. }
  613. }
  614. foreach ($this->bundles as $bundle) {
  615. $bundle->build($container);
  616. }
  617. $this->build($container);
  618. // ensure these extensions are implicitly loaded
  619. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  620. }
  621. /**
  622. * Gets a new ContainerBuilder instance used to build the service container.
  623. *
  624. * @return ContainerBuilder
  625. */
  626. protected function getContainerBuilder()
  627. {
  628. $container = new ContainerBuilder();
  629. $container->getParameterBag()->add($this->getKernelParameters());
  630. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
  631. $container->setProxyInstantiator(new RuntimeInstantiator());
  632. }
  633. return $container;
  634. }
  635. /**
  636. * Dumps the service container to PHP code in the cache.
  637. *
  638. * @param ConfigCache $cache The config cache
  639. * @param ContainerBuilder $container The service container
  640. * @param string $class The name of the class to generate
  641. * @param string $baseClass The name of the container's base class
  642. */
  643. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
  644. {
  645. // cache the container
  646. $dumper = new PhpDumper($container);
  647. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
  648. $dumper->setProxyDumper(new ProxyDumper(md5($cache->getPath())));
  649. }
  650. $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass, 'file' => $cache->getPath(), 'debug' => $this->debug));
  651. $cache->write($content, $container->getResources());
  652. }
  653. /**
  654. * Returns a loader for the container.
  655. *
  656. * @return DelegatingLoader The loader
  657. */
  658. protected function getContainerLoader(ContainerInterface $container)
  659. {
  660. $locator = new FileLocator($this);
  661. $resolver = new LoaderResolver(array(
  662. new XmlFileLoader($container, $locator),
  663. new YamlFileLoader($container, $locator),
  664. new IniFileLoader($container, $locator),
  665. new PhpFileLoader($container, $locator),
  666. new GlobFileLoader($locator),
  667. new DirectoryLoader($container, $locator),
  668. new ClosureLoader($container),
  669. ));
  670. return new DelegatingLoader($resolver);
  671. }
  672. /**
  673. * Removes comments from a PHP source string.
  674. *
  675. * We don't use the PHP php_strip_whitespace() function
  676. * as we want the content to be readable and well-formatted.
  677. *
  678. * @param string $source A PHP string
  679. *
  680. * @return string The PHP string with the comments removed
  681. */
  682. public static function stripComments($source)
  683. {
  684. if (!function_exists('token_get_all')) {
  685. return $source;
  686. }
  687. $rawChunk = '';
  688. $output = '';
  689. $tokens = token_get_all($source);
  690. $ignoreSpace = false;
  691. for ($i = 0; isset($tokens[$i]); ++$i) {
  692. $token = $tokens[$i];
  693. if (!isset($token[1]) || 'b"' === $token) {
  694. $rawChunk .= $token;
  695. } elseif (T_START_HEREDOC === $token[0]) {
  696. $output .= $rawChunk.$token[1];
  697. do {
  698. $token = $tokens[++$i];
  699. $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
  700. } while (T_END_HEREDOC !== $token[0]);
  701. $rawChunk = '';
  702. } elseif (T_WHITESPACE === $token[0]) {
  703. if ($ignoreSpace) {
  704. $ignoreSpace = false;
  705. continue;
  706. }
  707. // replace multiple new lines with a single newline
  708. $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
  709. } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  710. $ignoreSpace = true;
  711. } else {
  712. $rawChunk .= $token[1];
  713. // The PHP-open tag already has a new-line
  714. if (T_OPEN_TAG === $token[0]) {
  715. $ignoreSpace = true;
  716. }
  717. }
  718. }
  719. $output .= $rawChunk;
  720. if (\PHP_VERSION_ID >= 70000) {
  721. // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
  722. unset($tokens, $rawChunk);
  723. gc_mem_caches();
  724. }
  725. return $output;
  726. }
  727. public function serialize()
  728. {
  729. return serialize(array($this->environment, $this->debug));
  730. }
  731. public function unserialize($data)
  732. {
  733. if (\PHP_VERSION_ID >= 70000) {
  734. list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
  735. } else {
  736. list($environment, $debug) = unserialize($data);
  737. }
  738. $this->__construct($environment, $debug);
  739. }
  740. }