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

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