HttpKernel.php 10 KB

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