Kernel.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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\Component\DependencyInjection\ContainerInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  14. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  15. use Symfony\Component\DependencyInjection\Loader\DelegatingLoader;
  16. use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
  17. use Symfony\Component\DependencyInjection\Loader\LoaderResolver;
  18. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  19. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  20. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  21. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  22. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpKernel\HttpKernelInterface;
  25. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  26. use Symfony\Component\HttpKernel\DependencyInjection\Loader\FileLocator;
  27. /**
  28. * The Kernel is the heart of the Symfony system.
  29. *
  30. * It manages an environment made of bundles.
  31. *
  32. * @author Fabien Potencier <fabien.potencier@symfony-project.org>
  33. */
  34. abstract class Kernel implements KernelInterface
  35. {
  36. protected $bundles;
  37. protected $bundleMap;
  38. protected $container;
  39. protected $rootDir;
  40. protected $environment;
  41. protected $debug;
  42. protected $booted;
  43. protected $name;
  44. protected $startTime;
  45. const VERSION = '2.0.0-DEV';
  46. /**
  47. * Constructor.
  48. *
  49. * @param string $environment The environment
  50. * @param Boolean $debug Whether to enable debugging or not
  51. */
  52. public function __construct($environment, $debug)
  53. {
  54. $this->environment = $environment;
  55. $this->debug = (Boolean) $debug;
  56. $this->booted = false;
  57. $this->rootDir = realpath($this->registerRootDir());
  58. $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
  59. if ($this->debug) {
  60. ini_set('display_errors', 1);
  61. error_reporting(-1);
  62. $this->startTime = microtime(true);
  63. } else {
  64. ini_set('display_errors', 0);
  65. }
  66. }
  67. public function __clone()
  68. {
  69. if ($this->debug) {
  70. $this->startTime = microtime(true);
  71. }
  72. $this->booted = false;
  73. $this->container = null;
  74. }
  75. /**
  76. * Boots the current kernel.
  77. */
  78. public function boot()
  79. {
  80. if (true === $this->booted) {
  81. return;
  82. }
  83. // init bundles
  84. $this->initializeBundles();
  85. // init container
  86. $this->initializeContainer();
  87. foreach ($this->getBundles() as $bundle) {
  88. $bundle->setContainer($this->container);
  89. $bundle->boot();
  90. }
  91. $this->booted = true;
  92. }
  93. /**
  94. * Shutdowns the kernel.
  95. *
  96. * This method is mainly useful when doing functional testing.
  97. */
  98. public function shutdown()
  99. {
  100. $this->booted = false;
  101. foreach ($this->getBundles() as $bundle) {
  102. $bundle->shutdown();
  103. $bundle->setContainer(null);
  104. }
  105. $this->container = null;
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  111. {
  112. if (false === $this->booted) {
  113. $this->boot();
  114. }
  115. return $this->getHttpKernel()->handle($request, $type, $catch);
  116. }
  117. /**
  118. * Gets a http kernel from the container
  119. *
  120. * @return HttpKernel
  121. */
  122. protected function getHttpKernel()
  123. {
  124. return $this->container->get('http_kernel');
  125. }
  126. /**
  127. * Gets the registered bundle instances.
  128. *
  129. * @return array An array of registered bundle instances
  130. */
  131. public function getBundles()
  132. {
  133. return $this->bundles;
  134. }
  135. /**
  136. * Checks if a given class name belongs to an active bundle.
  137. *
  138. * @param string $class A class name
  139. *
  140. * @return Boolean true if the class belongs to an active bundle, false otherwise
  141. */
  142. public function isClassInActiveBundle($class)
  143. {
  144. foreach ($this->getBundles() as $bundle) {
  145. if (0 === strpos($class, $bundle->getNamespace())) {
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. /**
  152. * Returns a bundle and optionally its descendants by its name.
  153. *
  154. * @param string $name Bundle name
  155. * @param Boolean $first Whether to return the first bundle only or together with its descendants
  156. *
  157. * @return BundleInterface|Array A BundleInterface instance or an array of BundleInterface instances if $first is false
  158. *
  159. * @throws \InvalidArgumentException when the bundle is not enabled
  160. */
  161. public function getBundle($name, $first = true)
  162. {
  163. if (!isset($this->bundleMap[$name])) {
  164. throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled.', $name));
  165. }
  166. if (true === $first) {
  167. return $this->bundleMap[$name][0];
  168. } elseif (false === $first) {
  169. return $this->bundleMap[$name];
  170. }
  171. }
  172. /**
  173. * Returns the file path for a given resource.
  174. *
  175. * A Resource can be a file or a directory.
  176. *
  177. * The resource name must follow the following pattern:
  178. *
  179. * @BundleName/path/to/a/file.something
  180. *
  181. * where BundleName is the name of the bundle
  182. * and the remaining part is the relative path in the bundle.
  183. *
  184. * If $dir is passed, and the first segment of the path is Resources,
  185. * this method will look for a file named:
  186. *
  187. * $dir/BundleName/path/without/Resources
  188. *
  189. * @param string $name A resource name to locate
  190. * @param string $dir A directory where to look for the resource first
  191. * @param Boolean $first Whether to return the first path or paths for all matching bundles
  192. *
  193. * @return string|array The absolute path of the resource or an array if $first is false
  194. *
  195. * @throws \InvalidArgumentException if the file cannot be found or the name is not valid
  196. * @throws \RuntimeException if the name contains invalid/unsafe characters
  197. */
  198. public function locateResource($name, $dir = null, $first = true)
  199. {
  200. if ('@' !== $name[0]) {
  201. throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
  202. }
  203. if (false !== strpos($name, '..')) {
  204. throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
  205. }
  206. $name = substr($name, 1);
  207. list($bundle, $path) = explode('/', $name, 2);
  208. $isResource = 0 === strpos($path, 'Resources');
  209. $files = array();
  210. if (true === $isResource && null !== $dir && file_exists($file = $dir.'/'.$bundle.'/'.substr($path, 10))) {
  211. if ($first) {
  212. return $file;
  213. }
  214. $files[] = $file;
  215. }
  216. foreach ($this->getBundle($bundle, false) as $bundle) {
  217. if (file_exists($file = $bundle->getPath().'/'.$path)) {
  218. if ($first) {
  219. return $file;
  220. }
  221. $files[] = $file;
  222. }
  223. }
  224. if ($files) {
  225. return $files;
  226. }
  227. throw new \InvalidArgumentException(sprintf('Unable to find file "@%s".', $name));
  228. }
  229. public function getName()
  230. {
  231. return $this->name;
  232. }
  233. /**
  234. * Gets the environment.
  235. *
  236. * @return string The current environment
  237. */
  238. public function getEnvironment()
  239. {
  240. return $this->environment;
  241. }
  242. /**
  243. * Checks if debug mode is enabled.
  244. *
  245. * @return Boolean true if debug mode is enabled, false otherwise
  246. */
  247. public function isDebug()
  248. {
  249. return $this->debug;
  250. }
  251. /**
  252. * Gets the application root dir.
  253. *
  254. * @return string The application root dir
  255. */
  256. public function getRootDir()
  257. {
  258. return $this->rootDir;
  259. }
  260. /**
  261. * Gets the current container.
  262. *
  263. * @return ContainerInterface A ContainerInterface instance
  264. */
  265. public function getContainer()
  266. {
  267. return $this->container;
  268. }
  269. /**
  270. * Gets the request start time (not available if debug is disabled).
  271. *
  272. * @return integer The request start timestamp
  273. */
  274. public function getStartTime()
  275. {
  276. return $this->debug ? $this->startTime : -INF;
  277. }
  278. /**
  279. * Gets the cache directory.
  280. *
  281. * @return string The cache directory
  282. */
  283. public function getCacheDir()
  284. {
  285. return $this->rootDir.'/cache/'.$this->environment;
  286. }
  287. /**
  288. * Gets the log directory.
  289. *
  290. * @return string The log directory
  291. */
  292. public function getLogDir()
  293. {
  294. return $this->rootDir.'/logs';
  295. }
  296. /**
  297. * Initialize the data structures related to the bundle management:
  298. * - the bundles property maps a bundle name to the bundle instance,
  299. * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
  300. *
  301. * @throws \LogicException if two bundles share a common name
  302. * @throws \LogicException if a bundle tries to extend a non-registered bundle
  303. * @throws \LogicException if two bundles extend the same ancestor
  304. *
  305. */
  306. protected function initializeBundles()
  307. {
  308. // init bundles
  309. $this->bundles = array();
  310. $topMostBundles = array();
  311. $directChildren = array();
  312. foreach ($this->registerBundles() as $bundle) {
  313. $name = $bundle->getName();
  314. if (isset($this->bundles[$name])) {
  315. throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
  316. }
  317. $this->bundles[$name] = $bundle;
  318. if ($parentName = $bundle->getParent()) {
  319. if (isset($directChildren[$parentName])) {
  320. throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
  321. }
  322. $directChildren[$parentName] = $name;
  323. } else {
  324. $topMostBundles[$name] = $bundle;
  325. }
  326. }
  327. // look for orphans
  328. if (count($diff = array_values(array_diff(array_keys($directChildren), array_keys($this->bundles))))) {
  329. throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
  330. }
  331. // inheritance
  332. $this->bundleMap = array();
  333. foreach ($topMostBundles as $name => $bundle) {
  334. $bundleMap = array($bundle);
  335. $hierarchy = array($name);
  336. while (isset($directChildren[$name])) {
  337. $name = $directChildren[$name];
  338. array_unshift($bundleMap, $this->bundles[$name]);
  339. $hierarchy[] = $name;
  340. }
  341. foreach ($hierarchy as $bundle) {
  342. $this->bundleMap[$bundle] = $bundleMap;
  343. array_pop($bundleMap);
  344. }
  345. }
  346. }
  347. protected function initializeContainer()
  348. {
  349. $class = $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  350. $location = $this->getCacheDir().'/'.$class;
  351. $reload = $this->debug ? $this->needsReload($class, $location) : false;
  352. $fresh = false;
  353. if ($reload || !file_exists($location.'.php')) {
  354. $container = $this->buildContainer();
  355. $this->dumpContainer($container, $class, $location.'.php');
  356. $fresh = true;
  357. }
  358. require_once $location.'.php';
  359. $this->container = new $class();
  360. $this->container->set('kernel', $this);
  361. if ($fresh && 'cli' !== php_sapi_name()) {
  362. $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  363. }
  364. }
  365. protected function getKernelParameters()
  366. {
  367. $bundles = array();
  368. foreach ($this->bundles as $name => $bundle) {
  369. $bundles[$name] = get_class($bundle);
  370. }
  371. return array_merge(
  372. array(
  373. 'kernel.root_dir' => $this->rootDir,
  374. 'kernel.environment' => $this->environment,
  375. 'kernel.debug' => $this->debug,
  376. 'kernel.name' => $this->name,
  377. 'kernel.cache_dir' => $this->getCacheDir(),
  378. 'kernel.logs_dir' => $this->getLogDir(),
  379. 'kernel.bundles' => $bundles,
  380. 'kernel.charset' => 'UTF-8',
  381. ),
  382. $this->getEnvParameters()
  383. );
  384. }
  385. protected function getEnvParameters()
  386. {
  387. $parameters = array();
  388. foreach ($_SERVER as $key => $value) {
  389. if ('SYMFONY__' === substr($key, 0, 9)) {
  390. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  391. }
  392. }
  393. return $parameters;
  394. }
  395. protected function needsReload($class, $location)
  396. {
  397. if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
  398. return true;
  399. }
  400. $meta = unserialize(file_get_contents($location.'.meta'));
  401. $time = filemtime($location.'.php');
  402. foreach ($meta as $resource) {
  403. if (!$resource->isUptodate($time)) {
  404. return true;
  405. }
  406. }
  407. return false;
  408. }
  409. protected function buildContainer()
  410. {
  411. $parameterBag = new ParameterBag($this->getKernelParameters());
  412. $container = new ContainerBuilder($parameterBag);
  413. foreach ($this->bundles as $bundle) {
  414. $bundle->registerExtensions($container);
  415. if ($this->debug) {
  416. $container->addObjectResource($bundle);
  417. }
  418. }
  419. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  420. $container->merge($cont);
  421. }
  422. $container->compile();
  423. return $container;
  424. }
  425. protected function dumpContainer(ContainerBuilder $container, $class, $file)
  426. {
  427. foreach (array('cache', 'logs') as $name) {
  428. $dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
  429. if (!is_dir($dir)) {
  430. if (false === @mkdir($dir, 0777, true)) {
  431. die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
  432. }
  433. } elseif (!is_writable($dir)) {
  434. die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
  435. }
  436. }
  437. // cache the container
  438. $dumper = new PhpDumper($container);
  439. $content = $dumper->dump(array('class' => $class));
  440. if (!$this->debug) {
  441. $content = self::stripComments($content);
  442. }
  443. $this->writeCacheFile($file, $content);
  444. if ($this->debug) {
  445. $container->addObjectResource($this);
  446. // save the resources
  447. $this->writeCacheFile($this->getCacheDir().'/'.$class.'.meta', serialize($container->getResources()));
  448. }
  449. }
  450. protected function getContainerLoader(ContainerInterface $container)
  451. {
  452. $resolver = new LoaderResolver(array(
  453. new XmlFileLoader($container, new FileLocator($this)),
  454. new YamlFileLoader($container, new FileLocator($this)),
  455. new IniFileLoader($container, new FileLocator($this)),
  456. new PhpFileLoader($container, new FileLocator($this)),
  457. new ClosureLoader($container, new FileLocator($this)),
  458. ));
  459. return new DelegatingLoader($resolver);
  460. }
  461. /**
  462. * Removes comments from a PHP source string.
  463. *
  464. * We don't use the PHP php_strip_whitespace() function
  465. * as we want the content to be readable and well-formatted.
  466. *
  467. * @param string $source A PHP string
  468. *
  469. * @return string The PHP string with the comments removed
  470. */
  471. static public function stripComments($source)
  472. {
  473. if (!function_exists('token_get_all')) {
  474. return $source;
  475. }
  476. $output = '';
  477. foreach (token_get_all($source) as $token) {
  478. if (is_string($token)) {
  479. $output .= $token;
  480. } elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  481. $output .= $token[1];
  482. }
  483. }
  484. // replace multiple new lines with a single newline
  485. $output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
  486. return $output;
  487. }
  488. protected function writeCacheFile($file, $content)
  489. {
  490. $tmpFile = tempnam(dirname($file), basename($file));
  491. if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
  492. chmod($file, 0644);
  493. return;
  494. }
  495. throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
  496. }
  497. public function serialize()
  498. {
  499. return serialize(array($this->environment, $this->debug));
  500. }
  501. public function unserialize($data)
  502. {
  503. list($environment, $debug) = unserialize($data);
  504. $this->__construct($environment, $debug);
  505. }
  506. }