Kernel.php 19 KB

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