PageRenderTime 60ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/src/vendor/symfony/src/Symfony/Component/HttpKernel/Kernel.php

https://github.com/notbrain/symfony-sandbox
PHP | 464 lines | 354 code | 40 blank | 70 comment | 11 complexity | cf0cc8bfba18a504f03c7f3f3da917f3 MD5 | raw file
  1. <?php
  2. namespace Symfony\Component\HttpKernel;
  3. use Symfony\Component\DependencyInjection\ContainerInterface;
  4. use Symfony\Component\DependencyInjection\ContainerBuilder;
  5. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  6. use Symfony\Component\DependencyInjection\Resource\FileResource;
  7. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  8. use Symfony\Component\DependencyInjection\Loader\DelegatingLoader;
  9. use Symfony\Component\DependencyInjection\Loader\LoaderResolver;
  10. use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
  11. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  12. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  13. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  14. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  15. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpKernel\HttpKernelInterface;
  18. use Symfony\Component\HttpKernel\ClassCollectionLoader;
  19. /*
  20. * This file is part of the Symfony package.
  21. *
  22. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  23. *
  24. * For the full copyright and license information, please view the LICENSE
  25. * file that was distributed with this source code.
  26. */
  27. /**
  28. * The Kernel is the heart of the Symfony system. It manages an environment
  29. * that can host bundles.
  30. *
  31. * @author Fabien Potencier <fabien.potencier@symfony-project.org>
  32. */
  33. abstract class Kernel implements HttpKernelInterface, \Serializable
  34. {
  35. protected $bundles;
  36. protected $bundleDirs;
  37. protected $container;
  38. protected $rootDir;
  39. protected $environment;
  40. protected $debug;
  41. protected $booted;
  42. protected $name;
  43. protected $startTime;
  44. const VERSION = '2.0.0-DEV';
  45. /**
  46. * Constructor.
  47. *
  48. * @param string $environment The environment
  49. * @param Boolean $debug Whether to enable debugging or not
  50. */
  51. public function __construct($environment, $debug)
  52. {
  53. $this->environment = $environment;
  54. $this->debug = (Boolean) $debug;
  55. $this->booted = false;
  56. $this->rootDir = realpath($this->registerRootDir());
  57. $this->name = basename($this->rootDir);
  58. if ($this->debug) {
  59. ini_set('display_errors', 1);
  60. error_reporting(-1);
  61. $this->startTime = microtime(true);
  62. } else {
  63. ini_set('display_errors', 0);
  64. }
  65. }
  66. public function __clone()
  67. {
  68. if ($this->debug) {
  69. $this->startTime = microtime(true);
  70. }
  71. $this->booted = false;
  72. $this->container = null;
  73. }
  74. abstract public function registerRootDir();
  75. abstract public function registerBundles();
  76. abstract public function registerBundleDirs();
  77. abstract public function registerContainerConfiguration(LoaderInterface $loader);
  78. /**
  79. * Checks whether the current kernel has been booted or not.
  80. *
  81. * @return boolean $booted
  82. */
  83. public function isBooted()
  84. {
  85. return $this->booted;
  86. }
  87. /**
  88. * Boots the current kernel.
  89. *
  90. * This method boots the bundles, which MUST set
  91. * the DI container.
  92. *
  93. * @throws \LogicException When the Kernel is already booted
  94. */
  95. public function boot()
  96. {
  97. if (true === $this->booted) {
  98. throw new \LogicException('The kernel is already booted.');
  99. }
  100. if (!$this->isDebug()) {
  101. require_once __DIR__.'/bootstrap.php';
  102. }
  103. $this->bundles = $this->registerBundles();
  104. $this->bundleDirs = $this->registerBundleDirs();
  105. $this->container = $this->initializeContainer();
  106. // load core classes
  107. ClassCollectionLoader::load(
  108. $this->container->getParameter('kernel.compiled_classes'),
  109. $this->container->getParameter('kernel.cache_dir'),
  110. 'classes',
  111. $this->container->getParameter('kernel.debug'),
  112. true
  113. );
  114. foreach ($this->bundles as $bundle) {
  115. $bundle->setContainer($this->container);
  116. $bundle->boot();
  117. }
  118. $this->booted = true;
  119. }
  120. /**
  121. * Shutdowns the kernel.
  122. *
  123. * This method is mainly useful when doing functional testing.
  124. */
  125. public function shutdown()
  126. {
  127. $this->booted = false;
  128. foreach ($this->bundles as $bundle) {
  129. $bundle->shutdown();
  130. $bundle->setContainer(null);
  131. }
  132. $this->container = null;
  133. }
  134. /**
  135. * Reboots the kernel.
  136. *
  137. * This method is mainly useful when doing functional testing.
  138. *
  139. * It is a shortcut for the call to shutdown() and boot().
  140. */
  141. public function reboot()
  142. {
  143. $this->shutdown();
  144. $this->boot();
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  150. {
  151. if (false === $this->booted) {
  152. $this->boot();
  153. }
  154. return $this->container->get('http_kernel')->handle($request, $type, $catch);
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function getRequest()
  160. {
  161. return $this->container->get('http_kernel')->getRequest();
  162. }
  163. /**
  164. * Gets the directories where bundles can be stored.
  165. *
  166. * @return array An array of directories where bundles can be stored
  167. */
  168. public function getBundleDirs()
  169. {
  170. return $this->bundleDirs;
  171. }
  172. /**
  173. * Gets the registered bundle names.
  174. *
  175. * @return array An array of registered bundle names
  176. */
  177. public function getBundles()
  178. {
  179. return $this->bundles;
  180. }
  181. /**
  182. * Checks if a given class name belongs to an active bundle.
  183. *
  184. * @param string $class A class name
  185. *
  186. * @return Boolean true if the class belongs to an active bundle, false otherwise
  187. */
  188. public function isClassInActiveBundle($class)
  189. {
  190. foreach ($this->bundles as $bundle) {
  191. $bundleClass = get_class($bundle);
  192. if (0 === strpos($class, substr($bundleClass, 0, strrpos($bundleClass, '\\')))) {
  193. return true;
  194. }
  195. }
  196. return false;
  197. }
  198. public function getName()
  199. {
  200. return $this->name;
  201. }
  202. public function getSafeName()
  203. {
  204. return preg_replace('/[^a-zA-Z0-9_]+/', '', $this->name);
  205. }
  206. public function getEnvironment()
  207. {
  208. return $this->environment;
  209. }
  210. public function isDebug()
  211. {
  212. return $this->debug;
  213. }
  214. public function getRootDir()
  215. {
  216. return $this->rootDir;
  217. }
  218. public function getContainer()
  219. {
  220. return $this->container;
  221. }
  222. public function getStartTime()
  223. {
  224. return $this->debug ? $this->startTime : -INF;
  225. }
  226. public function getCacheDir()
  227. {
  228. return $this->rootDir.'/cache/'.$this->environment;
  229. }
  230. public function getLogDir()
  231. {
  232. return $this->rootDir.'/logs';
  233. }
  234. protected function initializeContainer()
  235. {
  236. $class = $this->getSafeName().ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  237. $location = $this->getCacheDir().'/'.$class;
  238. $reload = $this->debug ? $this->needsReload($class, $location) : false;
  239. if ($reload || !file_exists($location.'.php')) {
  240. $container = $this->buildContainer();
  241. $this->dumpContainer($container, $class, $location.'.php');
  242. }
  243. require_once $location.'.php';
  244. $container = new $class();
  245. $container->set('kernel', $this);
  246. return $container;
  247. }
  248. public function getKernelParameters()
  249. {
  250. $bundles = array();
  251. foreach ($this->bundles as $bundle) {
  252. $bundles[] = get_class($bundle);
  253. }
  254. return array_merge(
  255. array(
  256. 'kernel.root_dir' => $this->rootDir,
  257. 'kernel.environment' => $this->environment,
  258. 'kernel.debug' => $this->debug,
  259. 'kernel.name' => $this->name,
  260. 'kernel.cache_dir' => $this->getCacheDir(),
  261. 'kernel.logs_dir' => $this->getLogDir(),
  262. 'kernel.bundle_dirs' => $this->bundleDirs,
  263. 'kernel.bundles' => $bundles,
  264. 'kernel.charset' => 'UTF-8',
  265. ),
  266. $this->getEnvParameters()
  267. );
  268. }
  269. protected function getEnvParameters()
  270. {
  271. $parameters = array();
  272. foreach ($_SERVER as $key => $value) {
  273. if ('SYMFONY__' === substr($key, 0, 9)) {
  274. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  275. }
  276. }
  277. return $parameters;
  278. }
  279. protected function needsReload($class, $location)
  280. {
  281. if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
  282. return true;
  283. }
  284. $meta = unserialize(file_get_contents($location.'.meta'));
  285. $time = filemtime($location.'.php');
  286. foreach ($meta as $resource) {
  287. if (!$resource->isUptodate($time)) {
  288. return true;
  289. }
  290. }
  291. return false;
  292. }
  293. protected function buildContainer()
  294. {
  295. $parameterBag = new ParameterBag($this->getKernelParameters());
  296. $container = new ContainerBuilder($parameterBag);
  297. foreach ($this->bundles as $bundle) {
  298. $bundle->registerExtensions($container);
  299. if ($this->debug) {
  300. $container->addObjectResource($bundle);
  301. }
  302. }
  303. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  304. $container->merge($cont);
  305. }
  306. $container->compile();
  307. return $container;
  308. }
  309. protected function dumpContainer(ContainerBuilder $container, $class, $file)
  310. {
  311. foreach (array('cache', 'logs') as $name) {
  312. $dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
  313. if (!is_dir($dir)) {
  314. if (false === @mkdir($dir, 0777, true)) {
  315. die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
  316. }
  317. } elseif (!is_writable($dir)) {
  318. die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
  319. }
  320. }
  321. // cache the container
  322. $dumper = new PhpDumper($container);
  323. $content = $dumper->dump(array('class' => $class));
  324. if (!$this->debug) {
  325. $content = self::stripComments($content);
  326. }
  327. $this->writeCacheFile($file, $content);
  328. if ($this->debug) {
  329. $container->addObjectResource($this);
  330. // save the resources
  331. $this->writeCacheFile($this->getCacheDir().'/'.$class.'.meta', serialize($container->getResources()));
  332. }
  333. }
  334. protected function getContainerLoader(ContainerInterface $container)
  335. {
  336. $resolver = new LoaderResolver(array(
  337. new XmlFileLoader($container, $this->getBundleDirs()),
  338. new YamlFileLoader($container, $this->getBundleDirs()),
  339. new IniFileLoader($container, $this->getBundleDirs()),
  340. new PhpFileLoader($container, $this->getBundleDirs()),
  341. new ClosureLoader($container),
  342. ));
  343. return new DelegatingLoader($resolver);
  344. }
  345. /**
  346. * Removes comments from a PHP source string.
  347. *
  348. * We don't use the PHP php_strip_whitespace() function
  349. * as we want the content to be readable and well-formatted.
  350. *
  351. * @param string $source A PHP string
  352. *
  353. * @return string The PHP string with the comments removed
  354. */
  355. static public function stripComments($source)
  356. {
  357. if (!function_exists('token_get_all')) {
  358. return $source;
  359. }
  360. $output = '';
  361. foreach (token_get_all($source) as $token) {
  362. if (is_string($token)) {
  363. $output .= $token;
  364. } elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  365. $output .= $token[1];
  366. }
  367. }
  368. // replace multiple new lines with a single newline
  369. $output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
  370. return $output;
  371. }
  372. protected function writeCacheFile($file, $content)
  373. {
  374. $tmpFile = tempnam(dirname($file), basename($file));
  375. if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
  376. chmod($file, 0644);
  377. return;
  378. }
  379. throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
  380. }
  381. public function serialize()
  382. {
  383. return serialize(array($this->environment, $this->debug));
  384. }
  385. public function unserialize($data)
  386. {
  387. list($environment, $debug) = unserialize($data);
  388. $this->__construct($environment, $debug);
  389. }
  390. }