HttpKernel.php 9.5 KB

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