Kernel.php 19 KB

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