HttpKernel.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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\HttpKernel\Controller\ControllerResolverInterface;
  12. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  13. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  14. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  15. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  16. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  17. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  18. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  19. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  20. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\RequestStack;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  25. /**
  26. * HttpKernel notifies events to convert a Request object to a Response one.
  27. *
  28. * @author Fabien Potencier <fabien@symfony.com>
  29. *
  30. * @api
  31. */
  32. class HttpKernel implements HttpKernelInterface, TerminableInterface
  33. {
  34. protected $dispatcher;
  35. protected $resolver;
  36. protected $requestStack;
  37. /**
  38. * Constructor.
  39. *
  40. * @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance
  41. * @param ControllerResolverInterface $resolver A ControllerResolverInterface instance
  42. * @param RequestStack $requestStack A stack for master/sub requests
  43. *
  44. * @api
  45. */
  46. public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null)
  47. {
  48. $this->dispatcher = $dispatcher;
  49. $this->resolver = $resolver;
  50. $this->requestStack = $requestStack ?: new RequestStack();
  51. }
  52. /**
  53. * {@inheritdoc}
  54. *
  55. * @api
  56. */
  57. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  58. {
  59. try {
  60. return $this->handleRaw($request, $type);
  61. } catch (\Exception $e) {
  62. if (false === $catch) {
  63. $this->finishRequest($request, $type);
  64. throw $e;
  65. }
  66. return $this->handleException($e, $request, $type);
  67. }
  68. }
  69. /**
  70. * {@inheritdoc}
  71. *
  72. * @api
  73. */
  74. public function terminate(Request $request, Response $response)
  75. {
  76. $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));
  77. }
  78. /**
  79. * @throws \LogicException If the request stack is empty
  80. *
  81. * @internal
  82. */
  83. public function terminateWithException(\Exception $exception)
  84. {
  85. if (!$request = $this->requestStack->getMasterRequest()) {
  86. throw new \LogicException('Request stack is empty', 0, $exception);
  87. }
  88. $response = $this->handleException($exception, $request, self::MASTER_REQUEST);
  89. $response->sendHeaders();
  90. $response->sendContent();
  91. $this->terminate($request, $response);
  92. }
  93. /**
  94. * Handles a request to convert it to a response.
  95. *
  96. * Exceptions are not caught.
  97. *
  98. * @param Request $request A Request instance
  99. * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  100. *
  101. * @return Response A Response instance
  102. *
  103. * @throws \LogicException If one of the listener does not behave as expected
  104. * @throws NotFoundHttpException When controller cannot be found
  105. */
  106. private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
  107. {
  108. $this->requestStack->push($request);
  109. // request
  110. $event = new GetResponseEvent($this, $request, $type);
  111. $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);
  112. if ($event->hasResponse()) {
  113. return $this->filterResponse($event->getResponse(), $request, $type);
  114. }
  115. // load controller
  116. if (false === $controller = $this->resolver->getController($request)) {
  117. throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
  118. }
  119. $event = new FilterControllerEvent($this, $controller, $request, $type);
  120. $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event);
  121. $controller = $event->getController();
  122. // controller arguments
  123. $arguments = $this->resolver->getArguments($request, $controller);
  124. // call controller
  125. $response = call_user_func_array($controller, $arguments);
  126. // view
  127. if (!$response instanceof Response) {
  128. $event = new GetResponseForControllerResultEvent($this, $request, $type, $response);
  129. $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
  130. if ($event->hasResponse()) {
  131. $response = $event->getResponse();
  132. }
  133. if (!$response instanceof Response) {
  134. $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
  135. // the user may have forgotten to return something
  136. if (null === $response) {
  137. $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  138. }
  139. throw new \LogicException($msg);
  140. }
  141. }
  142. return $this->filterResponse($response, $request, $type);
  143. }
  144. /**
  145. * Filters a response object.
  146. *
  147. * @param Response $response A Response instance
  148. * @param Request $request An error message in case the response is not a Response object
  149. * @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  150. *
  151. * @return Response The filtered Response instance
  152. *
  153. * @throws \RuntimeException if the passed object is not a Response instance
  154. */
  155. private function filterResponse(Response $response, Request $request, $type)
  156. {
  157. $event = new FilterResponseEvent($this, $request, $type, $response);
  158. $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
  159. $this->finishRequest($request, $type);
  160. return $event->getResponse();
  161. }
  162. /**
  163. * Publishes the finish request event, then pop the request from the stack.
  164. *
  165. * Note that the order of the operations is important here, otherwise
  166. * operations such as {@link RequestStack::getParentRequest()} can lead to
  167. * weird results.
  168. *
  169. * @param Request $request
  170. * @param int $type
  171. */
  172. private function finishRequest(Request $request, $type)
  173. {
  174. $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this, $request, $type));
  175. $this->requestStack->pop();
  176. }
  177. /**
  178. * Handles an exception by trying to convert it to a Response.
  179. *
  180. * @param \Exception $e An \Exception instance
  181. * @param Request $request A Request instance
  182. * @param int $type The type of the request
  183. *
  184. * @return Response A Response instance
  185. *
  186. * @throws \Exception
  187. */
  188. private function handleException(\Exception $e, $request, $type)
  189. {
  190. $event = new GetResponseForExceptionEvent($this, $request, $type, $e);
  191. $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
  192. // a listener might have replaced the exception
  193. $e = $event->getException();
  194. if (!$event->hasResponse()) {
  195. $this->finishRequest($request, $type);
  196. throw $e;
  197. }
  198. $response = $event->getResponse();
  199. // the developer asked for a specific status code
  200. if ($response->headers->has('X-Status-Code')) {
  201. $response->setStatusCode($response->headers->get('X-Status-Code'));
  202. $response->headers->remove('X-Status-Code');
  203. } elseif (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  204. // ensure that we actually have an error response
  205. if ($e instanceof HttpExceptionInterface) {
  206. // keep the HTTP status code and headers
  207. $response->setStatusCode($e->getStatusCode());
  208. $response->headers->add($e->getHeaders());
  209. } else {
  210. $response->setStatusCode(500);
  211. }
  212. }
  213. try {
  214. return $this->filterResponse($response, $request, $type);
  215. } catch (\Exception $e) {
  216. return $response;
  217. }
  218. }
  219. private function varToString($var)
  220. {
  221. if (is_object($var)) {
  222. return sprintf('Object(%s)', get_class($var));
  223. }
  224. if (is_array($var)) {
  225. $a = array();
  226. foreach ($var as $k => $v) {
  227. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  228. }
  229. return sprintf('Array(%s)', implode(', ', $a));
  230. }
  231. if (is_resource($var)) {
  232. return sprintf('Resource(%s)', get_resource_type($var));
  233. }
  234. if (null === $var) {
  235. return 'null';
  236. }
  237. if (false === $var) {
  238. return 'false';
  239. }
  240. if (true === $var) {
  241. return 'true';
  242. }
  243. return (string) $var;
  244. }
  245. }