HttpKernel.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. try {
  36. $response = parent::handle($request, $type, $catch);
  37. } catch (\Exception $e) {
  38. $this->container->leaveScope('request');
  39. throw $e;
  40. }
  41. $this->container->leaveScope('request');
  42. return $response;
  43. }
  44. /**
  45. * Forwards the request to another controller.
  46. *
  47. * @param string $controller The controller name (a string like BlogBundle:Post:index)
  48. * @param array $attributes An array of request attributes
  49. * @param array $query An array of request query parameters
  50. *
  51. * @return Response A Response instance
  52. */
  53. public function forward($controller, array $attributes = array(), array $query = array())
  54. {
  55. $attributes['_controller'] = $controller;
  56. $subRequest = $this->container->get('request')->duplicate($query, null, $attributes);
  57. return $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  58. }
  59. /**
  60. * Renders a Controller and returns the Response content.
  61. *
  62. * Note that this method generates an esi:include tag only when both the standalone
  63. * option is set to true and the request has ESI capability (@see Symfony\Component\HttpKernel\HttpCache\ESI).
  64. *
  65. * Available options:
  66. *
  67. * * attributes: An array of request attributes (only when the first argument is a controller)
  68. * * query: An array of request query parameters (only when the first argument is a controller)
  69. * * ignore_errors: true to return an empty string in case of an error
  70. * * 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)
  71. * * standalone: whether to generate an esi:include tag or not when ESI is supported
  72. * * comment: a comment to add when returning an esi:include tag
  73. *
  74. * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI
  75. * @param array $options An array of options
  76. *
  77. * @return string The Response content
  78. */
  79. public function render($controller, array $options = array())
  80. {
  81. $options = array_merge(array(
  82. 'attributes' => array(),
  83. 'query' => array(),
  84. 'ignore_errors' => !$this->container->getParameter('kernel.debug'),
  85. 'alt' => array(),
  86. 'standalone' => false,
  87. 'comment' => '',
  88. ), $options);
  89. if (!is_array($options['alt'])) {
  90. $options['alt'] = array($options['alt']);
  91. }
  92. if (null === $this->esiSupport) {
  93. $this->esiSupport = $this->container->has('esi') && $this->container->get('esi')->hasSurrogateEsiCapability($this->container->get('request'));
  94. }
  95. if ($this->esiSupport && $options['standalone']) {
  96. $uri = $this->generateInternalUri($controller, $options['attributes'], $options['query']);
  97. $alt = '';
  98. if ($options['alt']) {
  99. $alt = $this->generateInternalUri($options['alt'][0], isset($options['alt'][1]) ? $options['alt'][1] : array(), isset($options['alt'][2]) ? $options['alt'][2] : array());
  100. }
  101. return $this->container->get('esi')->renderIncludeTag($uri, $alt, $options['ignore_errors'], $options['comment']);
  102. }
  103. $request = $this->container->get('request');
  104. // controller or URI?
  105. if (0 === strpos($controller, '/')) {
  106. $subRequest = Request::create($controller, 'get', array(), $request->cookies->all(), array(), $request->server->all());
  107. $subRequest->setSession($request->getSession());
  108. } else {
  109. $options['attributes']['_controller'] = $controller;
  110. $options['attributes']['_format'] = $request->getRequestFormat();
  111. $options['attributes']['_route'] = '_internal';
  112. $subRequest = $request->duplicate($options['query'], null, $options['attributes']);
  113. }
  114. try {
  115. $response = $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
  116. if (!$response->isSuccessful()) {
  117. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $request->getUri(), $response->getStatusCode()));
  118. }
  119. return $response->getContent();
  120. } catch (\Exception $e) {
  121. if ($options['alt']) {
  122. $alt = $options['alt'];
  123. unset($options['alt']);
  124. $options['attributes'] = isset($alt[1]) ? $alt[1] : array();
  125. $options['query'] = isset($alt[2]) ? $alt[2] : array();
  126. return $this->render($alt[0], $options);
  127. }
  128. if (!$options['ignore_errors']) {
  129. throw $e;
  130. }
  131. }
  132. }
  133. /**
  134. * Generates an internal URI for a given controller.
  135. *
  136. * This method uses the "_internal" route, which should be available.
  137. *
  138. * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI
  139. * @param array $attributes An array of request attributes
  140. * @param array $query An array of request query parameters
  141. *
  142. * @return string An internal URI
  143. */
  144. public function generateInternalUri($controller, array $attributes = array(), array $query = array())
  145. {
  146. if (0 === strpos($controller, '/')) {
  147. return $controller;
  148. }
  149. $path = http_build_query($attributes);
  150. $uri = $this->container->get('router')->generate('_internal', array(
  151. 'controller' => $controller,
  152. 'path' => $path ?: 'none',
  153. '_format' => $this->container->get('request')->getRequestFormat(),
  154. ));
  155. if ($queryString = http_build_query($query)) {
  156. $uri .= '?'.$queryString;
  157. }
  158. return $uri;
  159. }
  160. }