Kernel.php 17 KB

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