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

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