HttpKernel.php 9.9KB

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