Kernel.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. /**
  199. * Returns the Bundle name for a given class.
  200. *
  201. * @param string $class A class name
  202. *
  203. * @return string The Bundle name or null if the class does not belongs to a bundle
  204. */
  205. public function getBundleForClass($class)
  206. {
  207. $namespace = substr($class, 0, strrpos($class, '\\'));
  208. foreach (array_keys($this->getBundleDirs()) as $prefix) {
  209. if (0 === $pos = strpos($namespace, $prefix)) {
  210. return substr($namespace, strlen($prefix) + 1, strpos($class, 'Bundle\\') + 7);
  211. }
  212. }
  213. }
  214. public function getName()
  215. {
  216. return $this->name;
  217. }
  218. public function getSafeName()
  219. {
  220. return preg_replace('/[^a-zA-Z0-9_]+/', '', $this->name);
  221. }
  222. public function getEnvironment()
  223. {
  224. return $this->environment;
  225. }
  226. public function isDebug()
  227. {
  228. return $this->debug;
  229. }
  230. public function getRootDir()
  231. {
  232. return $this->rootDir;
  233. }
  234. public function getContainer()
  235. {
  236. return $this->container;
  237. }
  238. public function getStartTime()
  239. {
  240. return $this->debug ? $this->startTime : -INF;
  241. }
  242. public function getCacheDir()
  243. {
  244. return $this->rootDir.'/cache/'.$this->environment;
  245. }
  246. public function getLogDir()
  247. {
  248. return $this->rootDir.'/logs';
  249. }
  250. protected function initializeContainer()
  251. {
  252. $class = $this->getSafeName().ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  253. $location = $this->getCacheDir().'/'.$class;
  254. $reload = $this->debug ? $this->needsReload($class, $location) : false;
  255. if ($reload || !file_exists($location.'.php')) {
  256. $this->buildContainer($class, $location.'.php');
  257. }
  258. require_once $location.'.php';
  259. $container = new $class();
  260. $container->set('kernel', $this);
  261. return $container;
  262. }
  263. public function getKernelParameters()
  264. {
  265. $bundles = array();
  266. foreach ($this->bundles as $bundle) {
  267. $bundles[] = get_class($bundle);
  268. }
  269. return array_merge(
  270. array(
  271. 'kernel.root_dir' => $this->rootDir,
  272. 'kernel.environment' => $this->environment,
  273. 'kernel.debug' => $this->debug,
  274. 'kernel.name' => $this->name,
  275. 'kernel.cache_dir' => $this->getCacheDir(),
  276. 'kernel.logs_dir' => $this->getLogDir(),
  277. 'kernel.bundle_dirs' => $this->bundleDirs,
  278. 'kernel.bundles' => $bundles,
  279. 'kernel.charset' => 'UTF-8',
  280. ),
  281. $this->getEnvParameters()
  282. );
  283. }
  284. protected function getEnvParameters()
  285. {
  286. $parameters = array();
  287. foreach ($_SERVER as $key => $value) {
  288. if ('SYMFONY__' === substr($key, 0, 9)) {
  289. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  290. }
  291. }
  292. return $parameters;
  293. }
  294. protected function needsReload($class, $location)
  295. {
  296. if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
  297. return true;
  298. }
  299. $meta = unserialize(file_get_contents($location.'.meta'));
  300. $time = filemtime($location.'.php');
  301. foreach ($meta as $resource) {
  302. if (!$resource->isUptodate($time)) {
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. protected function buildContainer($class, $file)
  309. {
  310. $parameterBag = new ParameterBag($this->getKernelParameters());
  311. $container = new ContainerBuilder($parameterBag);
  312. foreach ($this->bundles as $bundle) {
  313. $bundle->registerExtensions($container);
  314. if ($this->debug) {
  315. $container->addObjectResource($bundle);
  316. }
  317. }
  318. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  319. $container->merge($cont);
  320. }
  321. $container->freeze();
  322. foreach (array('cache', 'logs') as $name) {
  323. $dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
  324. if (!is_dir($dir)) {
  325. if (false === @mkdir($dir, 0777, true)) {
  326. die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
  327. }
  328. } elseif (!is_writable($dir)) {
  329. die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
  330. }
  331. }
  332. // cache the container
  333. $dumper = new PhpDumper($container);
  334. $content = $dumper->dump(array('class' => $class));
  335. if (!$this->debug) {
  336. $content = self::stripComments($content);
  337. }
  338. $this->writeCacheFile($file, $content);
  339. if ($this->debug) {
  340. $container->addObjectResource($this);
  341. // save the resources
  342. $this->writeCacheFile($this->getCacheDir().'/'.$class.'.meta', serialize($container->getResources()));
  343. }
  344. }
  345. protected function getContainerLoader(ContainerInterface $container)
  346. {
  347. $resolver = new LoaderResolver(array(
  348. new XmlFileLoader($container, $this->getBundleDirs()),
  349. new YamlFileLoader($container, $this->getBundleDirs()),
  350. new IniFileLoader($container, $this->getBundleDirs()),
  351. new PhpFileLoader($container, $this->getBundleDirs()),
  352. new ClosureLoader($container),
  353. ));
  354. return new DelegatingLoader($resolver);
  355. }
  356. /**
  357. * Removes comments from a PHP source string.
  358. *
  359. * We don't use the PHP php_strip_whitespace() function
  360. * as we want the content to be readable and well-formatted.
  361. *
  362. * @param string $source A PHP string
  363. *
  364. * @return string The PHP string with the comments removed
  365. */
  366. static public function stripComments($source)
  367. {
  368. if (!function_exists('token_get_all')) {
  369. return $source;
  370. }
  371. $output = '';
  372. foreach (token_get_all($source) as $token) {
  373. if (is_string($token)) {
  374. $output .= $token;
  375. } elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  376. $output .= $token[1];
  377. }
  378. }
  379. // replace multiple new lines with a single newline
  380. $output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
  381. return $output;
  382. }
  383. protected function writeCacheFile($file, $content)
  384. {
  385. $tmpFile = tempnam(dirname($file), basename($file));
  386. if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
  387. chmod($file, 0644);
  388. return;
  389. }
  390. throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
  391. }
  392. public function serialize()
  393. {
  394. return serialize(array($this->environment, $this->debug));
  395. }
  396. public function unserialize($data)
  397. {
  398. list($environment, $debug) = unserialize($data);
  399. $this->__construct($environment, $debug);
  400. }
  401. }