HttpKernel.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. <?php
  2. /*
  3. * This file is part of the Symfony framework.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\Bundle\FrameworkBundle;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpKernel\HttpKernelInterface;
  13. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. use Symfony\Component\HttpKernel\HttpKernel as BaseHttpKernel;
  16. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  17. /**
  18. * This HttpKernel is used to manage scope changes of the DI container.
  19. *
  20. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  21. */
  22. class HttpKernel extends BaseHttpKernel
  23. {
  24. private $container;
  25. private $esiSupport;
  26. public function __construct(EventDispatcherInterface $dispatcher, ContainerInterface $container, ControllerResolverInterface $controllerResolver)
  27. {
  28. parent::__construct($dispatcher, $controllerResolver);
  29. $this->container = $container;
  30. }
  31. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  32. {
  33. $this->container->enterScope('request');
  34. $this->container->set('request', $request, 'request');
  35. $request->headers->set('X-Php-Ob-Level', ob_get_level());
  36. try {
  37. $response = parent::handle($request, $type, $catch);
  38. } catch (\Exception $e) {
  39. $this->container->leaveScope('request');
  40. throw $e;
  41. }
  42. $this->container->leaveScope('request');
  43. return $response;
  44. }
  45. /**
  46. * Forwards the request to another controller.
  47. *
  48. * @param string $controller The controller name (a string like BlogBundle:Post:index)
  49. * @param array $attributes An array of request attributes
  50. * @param array $query An array of request query parameters
  51. *
  52. * @return Response A Response instance
  53. */
  54. public function forward($controller, array $attributes = array(), array $query = array())
  55. {
  56. $attributes['_controller'] = $controller;
  57. $subRequest = $this->container->get('request')->duplicate($query, null, $attributes);
  58. return $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  59. }
  60. /**
  61. * Renders a Controller and returns the Response content.
  62. *
  63. * Note that this method generates an esi:include tag only when both the standalone
  64. * option is set to true and the request has ESI capability (@see Symfony\Component\HttpKernel\HttpCache\ESI).
  65. *
  66. * Available options:
  67. *
  68. * * attributes: An array of request attributes (only when the first argument is a controller)
  69. * * query: An array of request query parameters (only when the first argument is a controller)
  70. * * ignore_errors: true to return an empty string in case of an error
  71. * * alt: an alternative controller to execute in case of an error (can be a controller, a URI, or an array with the controller, the attributes, and the query arguments)
  72. * * standalone: whether to generate an esi:include tag or not when ESI is supported
  73. * * comment: a comment to add when returning an esi:include tag
  74. *
  75. * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI
  76. * @param array $options An array of options
  77. *
  78. * @return string The Response content
  79. */
  80. public function render($controller, array $options = array())
  81. {
  82. $options = array_merge(array(
  83. 'attributes' => array(),
  84. 'query' => array(),
  85. 'ignore_errors' => !$this->container->getParameter('kernel.debug'),
  86. 'alt' => array(),
  87. 'standalone' => false,
  88. 'comment' => '',
  89. ), $options);
  90. if (!is_array($options['alt'])) {
  91. $options['alt'] = array($options['alt']);
  92. }
  93. if (null === $this->esiSupport) {
  94. $this->esiSupport = $this->container->has('esi') && $this->container->get('esi')->hasSurrogateEsiCapability($this->container->get('request'));
  95. }
  96. if ($this->esiSupport && $options['standalone']) {
  97. $uri = $this->generateInternalUri($controller, $options['attributes'], $options['query']);
  98. $alt = '';
  99. if ($options['alt']) {
  100. $alt = $this->generateInternalUri($options['alt'][0], isset($options['alt'][1]) ? $options['alt'][1] : array(), isset($options['alt'][2]) ? $options['alt'][2] : array());
  101. }
  102. return $this->container->get('esi')->renderIncludeTag($uri, $alt, $options['ignore_errors'], $options['comment']);
  103. }
  104. $request = $this->container->get('request');
  105. // controller or URI?
  106. if (0 === strpos($controller, '/')) {
  107. $subRequest = Request::create($request->getUriForPath($controller), 'get', array(), $request->cookies->all(), array(), $request->server->all());
  108. if ($session = $request->getSession()) {
  109. $subRequest->setSession($session);
  110. }
  111. } else {
  112. $options['attributes']['_controller'] = $controller;
  113. $options['attributes']['_format'] = $request->getRequestFormat();
  114. $options['attributes']['_route'] = '_internal';
  115. $subRequest = $request->duplicate($options['query'], null, $options['attributes']);
  116. }
  117. $level = ob_get_level();
  118. try {
  119. $response = $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
  120. if (!$response->isSuccessful()) {
  121. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $request->getUri(), $response->getStatusCode()));
  122. }
  123. return $response->getContent();
  124. } catch (\Exception $e) {
  125. if ($options['alt']) {
  126. $alt = $options['alt'];
  127. unset($options['alt']);
  128. $options['attributes'] = isset($alt[1]) ? $alt[1] : array();
  129. $options['query'] = isset($alt[2]) ? $alt[2] : array();
  130. return $this->render($alt[0], $options);
  131. }
  132. if (!$options['ignore_errors']) {
  133. throw $e;
  134. }
  135. // let's clean up the output buffers that were created by the sub-request
  136. while (ob_get_level() > $level) {
  137. ob_get_clean();
  138. }
  139. }
  140. }
  141. /**
  142. * Generates an internal URI for a given controller.
  143. *
  144. * This method uses the "_internal" route, which should be available.
  145. *
  146. * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI
  147. * @param array $attributes An array of request attributes
  148. * @param array $query An array of request query parameters
  149. *
  150. * @return string An internal URI
  151. */
  152. public function generateInternalUri($controller, array $attributes = array(), array $query = array())
  153. {
  154. if (0 === strpos($controller, '/')) {
  155. return $controller;
  156. }
  157. $path = http_build_query($attributes);
  158. $uri = $this->container->get('router')->generate('_internal', array(
  159. 'controller' => $controller,
  160. 'path' => $path ?: 'none',
  161. '_format' => $this->container->get('request')->getRequestFormat(),
  162. ));
  163. if ($queryString = http_build_query($query)) {
  164. $uri .= '?'.$queryString;
  165. }
  166. return $uri;
  167. }
  168. }