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

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 HttpKernelInterfaceTerminableInterface
  47. {
  48.     protected $dispatcher;
  49.     protected $resolver;
  50.     protected $requestStack;
  51.     private ArgumentResolverInterface $argumentResolver;
  52.     private bool $catchThrowable;
  53.     public function __construct(EventDispatcherInterface $dispatcherControllerResolverInterface $resolverRequestStack $requestStack nullArgumentResolverInterface $argumentResolver nullbool $catchThrowable false)
  54.     {
  55.         $this->dispatcher $dispatcher;
  56.         $this->resolver $resolver;
  57.         $this->requestStack $requestStack ?? new RequestStack();
  58.         $this->argumentResolver $argumentResolver ?? new ArgumentResolver();
  59.         $this->catchThrowable $catchThrowable;
  60.         if (!$catchThrowable) {
  61.             trigger_deprecation('symfony/http-kernel''6.2''Starting from 7.0, "%s::handle()" will catch \Throwable exceptions and convert them to HttpFoundation responses. Pass $catchThrowable=true to adapt to this behavior now.'self::class);
  62.         }
  63.     }
  64.     public function handle(Request $requestint $type HttpKernelInterface::MAIN_REQUESTbool $catch true): Response
  65.     {
  66.         $request->headers->set('X-Php-Ob-Level', (string) ob_get_level());
  67.         $this->requestStack->push($request);
  68.         try {
  69.             return $this->handleRaw($request$type);
  70.         } catch (\Throwable $e) {
  71.             if (!$this->catchThrowable && !$e instanceof \Exception) {
  72.                 throw $e;
  73.             }
  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.     public function terminate(Request $requestResponse $response)
  87.     {
  88.         $this->dispatcher->dispatch(new TerminateEvent($this$request$response), KernelEvents::TERMINATE);
  89.     }
  90.     /**
  91.      * @internal
  92.      */
  93.     public function terminateWithException(\Throwable $exceptionRequest $request null)
  94.     {
  95.         if (!$request ??= $this->requestStack->getMainRequest()) {
  96.             throw $exception;
  97.         }
  98.         $response $this->handleThrowable($exception$requestself::MAIN_REQUEST);
  99.         $response->sendHeaders();
  100.         $response->sendContent();
  101.         $this->terminate($request$response);
  102.     }
  103.     /**
  104.      * Handles a request to convert it to a response.
  105.      *
  106.      * Exceptions are not caught.
  107.      *
  108.      * @throws \LogicException       If one of the listener does not behave as expected
  109.      * @throws NotFoundHttpException When controller cannot be found
  110.      */
  111.     private function handleRaw(Request $requestint $type self::MAIN_REQUEST): Response
  112.     {
  113.         // request
  114.         $event = new RequestEvent($this$request$type);
  115.         $this->dispatcher->dispatch($eventKernelEvents::REQUEST);
  116.         if ($event->hasResponse()) {
  117.             return $this->filterResponse($event->getResponse(), $request$type);
  118.         }
  119.         // load controller
  120.         if (false === $controller $this->resolver->getController($request)) {
  121.             throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.'$request->getPathInfo()));
  122.         }
  123.         $event = new ControllerEvent($this$controller$request$type);
  124.         $this->dispatcher->dispatch($eventKernelEvents::CONTROLLER);
  125.         $controller $event->getController();
  126.         // controller arguments
  127.         $arguments $this->argumentResolver->getArguments($request$controller$event->getControllerReflector());
  128.         $event = new ControllerArgumentsEvent($this$event$arguments$request$type);
  129.         $this->dispatcher->dispatch($eventKernelEvents::CONTROLLER_ARGUMENTS);
  130.         $controller $event->getController();
  131.         $arguments $event->getArguments();
  132.         // call controller
  133.         $response $controller(...$arguments);
  134.         // view
  135.         if (!$response instanceof Response) {
  136.             $event = new ViewEvent($this$request$type$response$event);
  137.             $this->dispatcher->dispatch($eventKernelEvents::VIEW);
  138.             if ($event->hasResponse()) {
  139.                 $response $event->getResponse();
  140.             } else {
  141.                 $msg sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.'$this->varToString($response));
  142.                 // the user may have forgotten to return something
  143.                 if (null === $response) {
  144.                     $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  145.                 }
  146.                 throw new ControllerDoesNotReturnResponseException($msg$controller__FILE____LINE__ 17);
  147.             }
  148.         }
  149.         return $this->filterResponse($response$request$type);
  150.     }
  151.     /**
  152.      * Filters a response object.
  153.      *
  154.      * @throws \RuntimeException if the passed object is not a Response instance
  155.      */
  156.     private function filterResponse(Response $responseRequest $requestint $type): Response
  157.     {
  158.         $event = new ResponseEvent($this$request$type$response);
  159.         $this->dispatcher->dispatch($eventKernelEvents::RESPONSE);
  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 $requestint $type)
  171.     {
  172.         $this->dispatcher->dispatch(new FinishRequestEvent($this$request$type), KernelEvents::FINISH_REQUEST);
  173.     }
  174.     /**
  175.      * Handles a throwable by trying to convert it to a Response.
  176.      *
  177.      * @throws \Throwable
  178.      */
  179.     private function handleThrowable(\Throwable $eRequest $requestint $type): Response
  180.     {
  181.         $event = new ExceptionEvent($this$request$type$e);
  182.         $this->dispatcher->dispatch($eventKernelEvents::EXCEPTION);
  183.         // a listener might have replaced the exception
  184.         $e $event->getThrowable();
  185.         if (!$event->hasResponse()) {
  186.             $this->finishRequest($request$type);
  187.             throw $e;
  188.         }
  189.         $response $event->getResponse();
  190.         // the developer asked for a specific status code
  191.         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  192.             // ensure that we actually have an error response
  193.             if ($e instanceof HttpExceptionInterface) {
  194.                 // keep the HTTP status code and headers
  195.                 $response->setStatusCode($e->getStatusCode());
  196.                 $response->headers->add($e->getHeaders());
  197.             } else {
  198.                 $response->setStatusCode(500);
  199.             }
  200.         }
  201.         try {
  202.             return $this->filterResponse($response$request$type);
  203.         } catch (\Throwable $e) {
  204.             if (!$this->catchThrowable && !$e instanceof \Exception) {
  205.                 throw $e;
  206.             }
  207.             return $response;
  208.         }
  209.     }
  210.     /**
  211.      * Returns a human-readable string for the specified variable.
  212.      */
  213.     private function varToString(mixed $var): string
  214.     {
  215.         if (\is_object($var)) {
  216.             return sprintf('an object of type %s'$var::class);
  217.         }
  218.         if (\is_array($var)) {
  219.             $a = [];
  220.             foreach ($var as $k => $v) {
  221.                 $a[] = sprintf('%s => ...'$k);
  222.             }
  223.             return sprintf('an array ([%s])'mb_substr(implode(', '$a), 0255));
  224.         }
  225.         if (\is_resource($var)) {
  226.             return sprintf('a resource (%s)'get_resource_type($var));
  227.         }
  228.         if (null === $var) {
  229.             return 'null';
  230.         }
  231.         if (false === $var) {
  232.             return 'a boolean value (false)';
  233.         }
  234.         if (true === $var) {
  235.             return 'a boolean value (true)';
  236.         }
  237.         if (\is_string($var)) {
  238.             return sprintf('a string ("%s%s")'mb_substr($var0255), mb_strlen($var) > 255 '...' '');
  239.         }
  240.         if (is_numeric($var)) {
  241.             return sprintf('a number (%s)', (string) $var);
  242.         }
  243.         return (string) $var;
  244.     }
  245. }