vendor/symfony/http-kernel/HttpKernel.php line 220

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