Kernel.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 = $this->getRootDir();
  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. /**
  231. * Gets the name of the kernel
  232. *
  233. * @return string The kernel name
  234. */
  235. public function getName()
  236. {
  237. return $this->name;
  238. }
  239. /**
  240. * Gets the environment.
  241. *
  242. * @return string The current environment
  243. */
  244. public function getEnvironment()
  245. {
  246. return $this->environment;
  247. }
  248. /**
  249. * Checks if debug mode is enabled.
  250. *
  251. * @return Boolean true if debug mode is enabled, false otherwise
  252. */
  253. public function isDebug()
  254. {
  255. return $this->debug;
  256. }
  257. /**
  258. * Gets the application root dir.
  259. *
  260. * @return string The application root dir
  261. */
  262. public function getRootDir()
  263. {
  264. if (null === $this->rootDir) {
  265. $r = new \ReflectionObject($this);
  266. $this->rootDir = dirname($r->getFileName());
  267. }
  268. return $this->rootDir;
  269. }
  270. /**
  271. * Gets the current container.
  272. *
  273. * @return ContainerInterface A ContainerInterface instance
  274. */
  275. public function getContainer()
  276. {
  277. return $this->container;
  278. }
  279. /**
  280. * Gets the request start time (not available if debug is disabled).
  281. *
  282. * @return integer The request start timestamp
  283. */
  284. public function getStartTime()
  285. {
  286. return $this->debug ? $this->startTime : -INF;
  287. }
  288. /**
  289. * Gets the cache directory.
  290. *
  291. * @return string The cache directory
  292. */
  293. public function getCacheDir()
  294. {
  295. return $this->rootDir.'/cache/'.$this->environment;
  296. }
  297. /**
  298. * Gets the log directory.
  299. *
  300. * @return string The log directory
  301. */
  302. public function getLogDir()
  303. {
  304. return $this->rootDir.'/logs';
  305. }
  306. /**
  307. * Initializes the data structures related to the bundle management.
  308. *
  309. * - the bundles property maps a bundle name to the bundle instance,
  310. * - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
  311. *
  312. * @throws \LogicException if two bundles share a common name
  313. * @throws \LogicException if a bundle tries to extend a non-registered bundle
  314. * @throws \LogicException if two bundles extend the same ancestor
  315. */
  316. protected function initializeBundles()
  317. {
  318. // init bundles
  319. $this->bundles = array();
  320. $topMostBundles = array();
  321. $directChildren = array();
  322. foreach ($this->registerBundles() as $bundle) {
  323. $name = $bundle->getName();
  324. if (isset($this->bundles[$name])) {
  325. throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
  326. }
  327. $this->bundles[$name] = $bundle;
  328. if ($parentName = $bundle->getParent()) {
  329. if (isset($directChildren[$parentName])) {
  330. throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
  331. }
  332. $directChildren[$parentName] = $name;
  333. } else {
  334. $topMostBundles[$name] = $bundle;
  335. }
  336. }
  337. // look for orphans
  338. if (count($diff = array_values(array_diff(array_keys($directChildren), array_keys($this->bundles))))) {
  339. throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
  340. }
  341. // inheritance
  342. $this->bundleMap = array();
  343. foreach ($topMostBundles as $name => $bundle) {
  344. $bundleMap = array($bundle);
  345. $hierarchy = array($name);
  346. while (isset($directChildren[$name])) {
  347. $name = $directChildren[$name];
  348. array_unshift($bundleMap, $this->bundles[$name]);
  349. $hierarchy[] = $name;
  350. }
  351. foreach ($hierarchy as $bundle) {
  352. $this->bundleMap[$bundle] = $bundleMap;
  353. array_pop($bundleMap);
  354. }
  355. }
  356. }
  357. /**
  358. * Gets the container class.
  359. *
  360. * @return string The container class
  361. */
  362. protected function getContainerClass()
  363. {
  364. return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
  365. }
  366. /**
  367. * Initializes the service container.
  368. *
  369. * The cached version of the service container is used when fresh, otherwise the
  370. * container is built.
  371. */
  372. protected function initializeContainer()
  373. {
  374. $class = $this->getContainerClass();
  375. $cache = new ConfigCache($this->getCacheDir().'/'.$class.'.php', $this->debug);
  376. $fresh = true;
  377. if (!$cache->isFresh()) {
  378. $container = $this->buildContainer();
  379. $this->dumpContainer($cache, $container, $class);
  380. $fresh = false;
  381. }
  382. require_once $cache;
  383. $this->container = new $class();
  384. $this->container->set('kernel', $this);
  385. if (!$fresh && 'cli' !== php_sapi_name()) {
  386. $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  387. }
  388. }
  389. /**
  390. * Returns the kernel parameters.
  391. *
  392. * @return array An array of kernel parameters
  393. */
  394. protected function getKernelParameters()
  395. {
  396. $bundles = array();
  397. foreach ($this->bundles as $name => $bundle) {
  398. $bundles[$name] = get_class($bundle);
  399. }
  400. return array_merge(
  401. array(
  402. 'kernel.root_dir' => $this->rootDir,
  403. 'kernel.environment' => $this->environment,
  404. 'kernel.debug' => $this->debug,
  405. 'kernel.name' => $this->name,
  406. 'kernel.cache_dir' => $this->getCacheDir(),
  407. 'kernel.logs_dir' => $this->getLogDir(),
  408. 'kernel.bundles' => $bundles,
  409. 'kernel.charset' => 'UTF-8',
  410. 'kernel.container_class' => $this->getContainerClass(),
  411. ),
  412. $this->getEnvParameters()
  413. );
  414. }
  415. /**
  416. * Gets the environment parameters.
  417. *
  418. * Only the parameters starting with "SYMFONY__" are considered.
  419. *
  420. * @return array An array of parameters
  421. */
  422. protected function getEnvParameters()
  423. {
  424. $parameters = array();
  425. foreach ($_SERVER as $key => $value) {
  426. if ('SYMFONY__' === substr($key, 0, 9)) {
  427. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  428. }
  429. }
  430. return $parameters;
  431. }
  432. /**
  433. * Builds the service container.
  434. *
  435. * @return ContainerBuilder The compiled service container
  436. */
  437. protected function buildContainer()
  438. {
  439. $parameterBag = new ParameterBag($this->getKernelParameters());
  440. $container = new ContainerBuilder($parameterBag);
  441. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass());
  442. foreach ($this->bundles as $bundle) {
  443. $bundle->build($container);
  444. if ($this->debug) {
  445. $container->addObjectResource($bundle);
  446. }
  447. }
  448. $container->addObjectResource($this);
  449. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  450. $container->merge($cont);
  451. }
  452. foreach (array('cache', 'logs') as $name) {
  453. $dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
  454. if (!is_dir($dir)) {
  455. if (false === @mkdir($dir, 0777, true)) {
  456. exit(sprintf("Unable to create the %s directory (%s)\n", $name, dirname($dir)));
  457. }
  458. } elseif (!is_writable($dir)) {
  459. exit(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
  460. }
  461. }
  462. $container->compile();
  463. return $container;
  464. }
  465. /**
  466. * Dumps the service container to PHP code in the cache.
  467. *
  468. * @param ConfigCache $cache The config cache
  469. * @param ContainerBuilder $container The service container
  470. * @param string $class The name of the class to generate
  471. */
  472. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class)
  473. {
  474. // cache the container
  475. $dumper = new PhpDumper($container);
  476. $content = $dumper->dump(array('class' => $class));
  477. if (!$this->debug) {
  478. $content = self::stripComments($content);
  479. }
  480. $cache->write($content, $container->getResources());
  481. }
  482. /**
  483. * Returns a loader for the container.
  484. *
  485. * @param ContainerInterface $container The service container
  486. *
  487. * @return DelegatingLoader The loader
  488. */
  489. protected function getContainerLoader(ContainerInterface $container)
  490. {
  491. $locator = new FileLocator($this);
  492. $resolver = new LoaderResolver(array(
  493. new XmlFileLoader($container, $locator),
  494. new YamlFileLoader($container, $locator),
  495. new IniFileLoader($container, $locator),
  496. new PhpFileLoader($container, $locator),
  497. new ClosureLoader($container, $locator),
  498. ));
  499. return new DelegatingLoader($resolver);
  500. }
  501. /**
  502. * Removes comments from a PHP source string.
  503. *
  504. * We don't use the PHP php_strip_whitespace() function
  505. * as we want the content to be readable and well-formatted.
  506. *
  507. * @param string $source A PHP string
  508. *
  509. * @return string The PHP string with the comments removed
  510. */
  511. static public function stripComments($source)
  512. {
  513. if (!function_exists('token_get_all')) {
  514. return $source;
  515. }
  516. $output = '';
  517. foreach (token_get_all($source) as $token) {
  518. if (is_string($token)) {
  519. $output .= $token;
  520. } elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  521. $output .= $token[1];
  522. }
  523. }
  524. // replace multiple new lines with a single newline
  525. $output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
  526. return $output;
  527. }
  528. public function serialize()
  529. {
  530. return serialize(array($this->environment, $this->debug));
  531. }
  532. public function unserialize($data)
  533. {
  534. list($environment, $debug) = unserialize($data);
  535. $this->__construct($environment, $debug);
  536. }
  537. }