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

  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 $handleAllThrowables;
  53.     public function __construct(EventDispatcherInterface $dispatcherControllerResolverInterface $resolverRequestStack $requestStack nullArgumentResolverInterface $argumentResolver nullbool $handleAllThrowables false)
  54.     {
  55.         $this->dispatcher $dispatcher;
  56.         $this->resolver $resolver;
  57.         $this->requestStack $requestStack ?? new RequestStack();
  58.         $this->argumentResolver $argumentResolver ?? new ArgumentResolver();
  59.         $this->handleAllThrowables $handleAllThrowables;
  60.     }
  61.     public function handle(Request $requestint $type HttpKernelInterface::MAIN_REQUESTbool $catch true): Response
  62.     {
  63.         $request->headers->set('X-Php-Ob-Level', (string) ob_get_level());
  64.         $this->requestStack->push($request);
  65.         try {
  66.             return $this->handleRaw($request$type);
  67.         } catch (\Throwable $e) {
  68.             if ($e instanceof \Error && !$this->handleAllThrowables) {
  69.                 throw $e;
  70.             }
  71.             if ($e instanceof RequestExceptionInterface) {
  72.                 $e = new BadRequestHttpException($e->getMessage(), $e);
  73.             }
  74.             if (false === $catch) {
  75.                 $this->finishRequest($request$type);
  76.                 throw $e;
  77.             }
  78.             return $this->handleThrowable($e$request$type);
  79.         } finally {
  80.             $this->requestStack->pop();
  81.         }
  82.     }
  83.     public function terminate(Request $requestResponse $response)
  84.     {
  85.         $this->dispatcher->dispatch(new TerminateEvent($this$request$response), KernelEvents::TERMINATE);
  86.     }
  87.     /**
  88.      * @internal
  89.      */
  90.     public function terminateWithException(\Throwable $exceptionRequest $request null)
  91.     {
  92.         if (!$request ??= $this->requestStack->getMainRequest()) {
  93.             throw $exception;
  94.         }
  95.         if ($pop $request !== $this->requestStack->getMainRequest()) {
  96.             $this->requestStack->push($request);
  97.         }
  98.         try {
  99.             $response $this->handleThrowable($exception$requestself::MAIN_REQUEST);
  100.         } finally {
  101.             if ($pop) {
  102.                 $this->requestStack->pop();
  103.             }
  104.         }
  105.         $response->sendHeaders();
  106.         $response->sendContent();
  107.         $this->terminate($request$response);
  108.     }
  109.     /**
  110.      * Handles a request to convert it to a response.
  111.      *
  112.      * Exceptions are not caught.
  113.      *
  114.      * @throws \LogicException       If one of the listener does not behave as expected
  115.      * @throws NotFoundHttpException When controller cannot be found
  116.      */
  117.     private function handleRaw(Request $requestint $type self::MAIN_REQUEST): Response
  118.     {
  119.         // request
  120.         $event = new RequestEvent($this$request$type);
  121.         $this->dispatcher->dispatch($eventKernelEvents::REQUEST);
  122.         if ($event->hasResponse()) {
  123.             return $this->filterResponse($event->getResponse(), $request$type);
  124.         }
  125.         // load controller
  126.         if (false === $controller $this->resolver->getController($request)) {
  127.             throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.'$request->getPathInfo()));
  128.         }
  129.         $event = new ControllerEvent($this$controller$request$type);
  130.         $this->dispatcher->dispatch($eventKernelEvents::CONTROLLER);
  131.         $controller $event->getController();
  132.         // controller arguments
  133.         $arguments $this->argumentResolver->getArguments($request$controller$event->getControllerReflector());
  134.         $event = new ControllerArgumentsEvent($this$event$arguments$request$type);
  135.         $this->dispatcher->dispatch($eventKernelEvents::CONTROLLER_ARGUMENTS);
  136.         $controller $event->getController();
  137.         $arguments $event->getArguments();
  138.         // call controller
  139.         $response $controller(...$arguments);
  140.         // view
  141.         if (!$response instanceof Response) {
  142.             $event = new ViewEvent($this$request$type$response$event);
  143.             $this->dispatcher->dispatch($eventKernelEvents::VIEW);
  144.             if ($event->hasResponse()) {
  145.                 $response $event->getResponse();
  146.             } else {
  147.                 $msg sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.'$this->varToString($response));
  148.                 // the user may have forgotten to return something
  149.                 if (null === $response) {
  150.                     $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  151.                 }
  152.                 throw new ControllerDoesNotReturnResponseException($msg$controller__FILE____LINE__ 17);
  153.             }
  154.         }
  155.         return $this->filterResponse($response$request$type);
  156.     }
  157.     /**
  158.      * Filters a response object.
  159.      *
  160.      * @throws \RuntimeException if the passed object is not a Response instance
  161.      */
  162.     private function filterResponse(Response $responseRequest $requestint $type): Response
  163.     {
  164.         $event = new ResponseEvent($this$request$type$response);
  165.         $this->dispatcher->dispatch($eventKernelEvents::RESPONSE);
  166.         $this->finishRequest($request$type);
  167.         return $event->getResponse();
  168.     }
  169.     /**
  170.      * Publishes the finish request event, then pop the request from the stack.
  171.      *
  172.      * Note that the order of the operations is important here, otherwise
  173.      * operations such as {@link RequestStack::getParentRequest()} can lead to
  174.      * weird results.
  175.      */
  176.     private function finishRequest(Request $requestint $type)
  177.     {
  178.         $this->dispatcher->dispatch(new FinishRequestEvent($this$request$type), KernelEvents::FINISH_REQUEST);
  179.     }
  180.     /**
  181.      * Handles a throwable by trying to convert it to a Response.
  182.      */
  183.     private function handleThrowable(\Throwable $eRequest $requestint $type): Response
  184.     {
  185.         $event = new ExceptionEvent($this$request$type$e);
  186.         $this->dispatcher->dispatch($eventKernelEvents::EXCEPTION);
  187.         // a listener might have replaced the exception
  188.         $e $event->getThrowable();
  189.         if (!$event->hasResponse()) {
  190.             $this->finishRequest($request$type);
  191.             throw $e;
  192.         }
  193.         $response $event->getResponse();
  194.         // the developer asked for a specific status code
  195.         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  196.             // ensure that we actually have an error response
  197.             if ($e instanceof HttpExceptionInterface) {
  198.                 // keep the HTTP status code and headers
  199.                 $response->setStatusCode($e->getStatusCode());
  200.                 $response->headers->add($e->getHeaders());
  201.             } else {
  202.                 $response->setStatusCode(500);
  203.             }
  204.         }
  205.         try {
  206.             return $this->filterResponse($response$request$type);
  207.         } catch (\Throwable $e) {
  208.             if ($e instanceof \Error && !$this->handleAllThrowables) {
  209.                 throw $e;
  210.             }
  211.             return $response;
  212.         }
  213.     }
  214.     /**
  215.      * Returns a human-readable string for the specified variable.
  216.      */
  217.     private function varToString(mixed $var): string
  218.     {
  219.         if (\is_object($var)) {
  220.             return sprintf('an object of type %s'$var::class);
  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), 0255));
  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($var0255), 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. }