HttpKernel.php 9.5 KB

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