HttpKernel.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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\HttpFoundation\Exception\RequestExceptionInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
  16. use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
  17. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  18. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  19. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  20. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  21. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  22. use Symfony\Component\HttpKernel\Event\RequestEvent;
  23. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  24. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  25. use Symfony\Component\HttpKernel\Event\ViewEvent;
  26. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  27. use Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException;
  28. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  29. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  30. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  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, int $type = HttpKernelInterface::MASTER_REQUEST, bool $catch = true)
  56. {
  57. $request->headers->set('X-Php-Ob-Level', (string) 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->handleThrowable($e, $request, $type);
  69. }
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function terminate(Request $request, Response $response)
  75. {
  76. $this->dispatcher->dispatch(new TerminateEvent($this, $request, $response), KernelEvents::TERMINATE);
  77. }
  78. /**
  79. * @internal
  80. */
  81. public function terminateWithException(\Throwable $exception, Request $request = null)
  82. {
  83. if (!$request = $request ?: $this->requestStack->getMasterRequest()) {
  84. throw $exception;
  85. }
  86. $response = $this->handleThrowable($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. * @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, int $type = self::MASTER_REQUEST): Response
  100. {
  101. $this->requestStack->push($request);
  102. // request
  103. $event = new RequestEvent($this, $request, $type);
  104. $this->dispatcher->dispatch($event, KernelEvents::REQUEST);
  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 ControllerEvent($this, $controller, $request, $type);
  113. $this->dispatcher->dispatch($event, KernelEvents::CONTROLLER);
  114. $controller = $event->getController();
  115. // controller arguments
  116. $arguments = $this->argumentResolver->getArguments($request, $controller);
  117. $event = new ControllerArgumentsEvent($this, $controller, $arguments, $request, $type);
  118. $this->dispatcher->dispatch($event, KernelEvents::CONTROLLER_ARGUMENTS);
  119. $controller = $event->getController();
  120. $arguments = $event->getArguments();
  121. // call controller
  122. $response = $controller(...$arguments);
  123. // view
  124. if (!$response instanceof Response) {
  125. $event = new ViewEvent($this, $request, $type, $response);
  126. $this->dispatcher->dispatch($event, KernelEvents::VIEW);
  127. if ($event->hasResponse()) {
  128. $response = $event->getResponse();
  129. } else {
  130. $msg = sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.', $this->varToString($response));
  131. // the user may have forgotten to return something
  132. if (null === $response) {
  133. $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  134. }
  135. throw new ControllerDoesNotReturnResponseException($msg, $controller, __FILE__, __LINE__ - 17);
  136. }
  137. }
  138. return $this->filterResponse($response, $request, $type);
  139. }
  140. /**
  141. * Filters a response object.
  142. *
  143. * @throws \RuntimeException if the passed object is not a Response instance
  144. */
  145. private function filterResponse(Response $response, Request $request, int $type): Response
  146. {
  147. $event = new ResponseEvent($this, $request, $type, $response);
  148. $this->dispatcher->dispatch($event, KernelEvents::RESPONSE);
  149. $this->finishRequest($request, $type);
  150. return $event->getResponse();
  151. }
  152. /**
  153. * Publishes the finish request event, then pop the request from the stack.
  154. *
  155. * Note that the order of the operations is important here, otherwise
  156. * operations such as {@link RequestStack::getParentRequest()} can lead to
  157. * weird results.
  158. */
  159. private function finishRequest(Request $request, int $type)
  160. {
  161. $this->dispatcher->dispatch(new FinishRequestEvent($this, $request, $type), KernelEvents::FINISH_REQUEST);
  162. $this->requestStack->pop();
  163. }
  164. /**
  165. * Handles a throwable by trying to convert it to a Response.
  166. *
  167. * @throws \Exception
  168. */
  169. private function handleThrowable(\Throwable $e, Request $request, int $type): Response
  170. {
  171. $event = new ExceptionEvent($this, $request, $type, $e);
  172. $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);
  173. // a listener might have replaced the exception
  174. $e = $event->getThrowable();
  175. if (!$event->hasResponse()) {
  176. $this->finishRequest($request, $type);
  177. throw $e;
  178. }
  179. $response = $event->getResponse();
  180. // the developer asked for a specific status code
  181. if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  182. // ensure that we actually have an error response
  183. if ($e instanceof HttpExceptionInterface) {
  184. // keep the HTTP status code and headers
  185. $response->setStatusCode($e->getStatusCode());
  186. $response->headers->add($e->getHeaders());
  187. } else {
  188. $response->setStatusCode(500);
  189. }
  190. }
  191. try {
  192. return $this->filterResponse($response, $request, $type);
  193. } catch (\Exception $e) {
  194. return $response;
  195. }
  196. }
  197. /**
  198. * Returns a human-readable string for the specified variable.
  199. */
  200. private function varToString($var): string
  201. {
  202. if (\is_object($var)) {
  203. return sprintf('an object of type %s', \get_class($var));
  204. }
  205. if (\is_array($var)) {
  206. $a = [];
  207. foreach ($var as $k => $v) {
  208. $a[] = sprintf('%s => ...', $k);
  209. }
  210. return sprintf('an array ([%s])', mb_substr(implode(', ', $a), 0, 255));
  211. }
  212. if (\is_resource($var)) {
  213. return sprintf('a resource (%s)', get_resource_type($var));
  214. }
  215. if (null === $var) {
  216. return 'null';
  217. }
  218. if (false === $var) {
  219. return 'a boolean value (false)';
  220. }
  221. if (true === $var) {
  222. return 'a boolean value (true)';
  223. }
  224. if (\is_string($var)) {
  225. return sprintf('a string ("%s%s")', mb_substr($var, 0, 255), mb_strlen($var) > 255 ? '...' : '');
  226. }
  227. if (is_numeric($var)) {
  228. return sprintf('a number (%s)', (string) $var);
  229. }
  230. return (string) $var;
  231. }
  232. }