HttpKernel.php 10 KB

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