HttpKernel.php 9.7 KB

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