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

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\EventDispatcher\LegacyEventDispatcherProxy;
  12. use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
  17. use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
  18. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  19. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  20. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  21. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  22. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  23. use Symfony\Component\HttpKernel\Event\RequestEvent;
  24. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  25. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  26. use Symfony\Component\HttpKernel\Event\ViewEvent;
  27. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  28. use Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException;
  29. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  30. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  31. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  32. // Help opcache.preload discover always-needed symbols
  33. class_exists(LegacyEventDispatcherProxy::class);
  34. class_exists(ControllerArgumentsEvent::class);
  35. class_exists(ControllerEvent::class);
  36. class_exists(ExceptionEvent::class);
  37. class_exists(FinishRequestEvent::class);
  38. class_exists(RequestEvent::class);
  39. class_exists(ResponseEvent::class);
  40. class_exists(TerminateEvent::class);
  41. class_exists(ViewEvent::class);
  42. class_exists(KernelEvents::class);
  43. /**
  44.  * HttpKernel notifies events to convert a Request object to a Response one.
  45.  *
  46.  * @author Fabien Potencier <fabien@symfony.com>
  47.  */
  48. class HttpKernel implements HttpKernelInterfaceTerminableInterface
  49. {
  50.     protected $dispatcher;
  51.     protected $resolver;
  52.     protected $requestStack;
  53.     private $argumentResolver;
  54.     public function __construct(EventDispatcherInterface $dispatcherControllerResolverInterface $resolverRequestStack $requestStack nullArgumentResolverInterface $argumentResolver null)
  55.     {
  56.         $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  57.         $this->resolver $resolver;
  58.         $this->requestStack $requestStack ?? new RequestStack();
  59.         $this->argumentResolver $argumentResolver;
  60.         if (null === $this->argumentResolver) {
  61.             $this->argumentResolver = new ArgumentResolver();
  62.         }
  63.     }
  64.     /**
  65.      * {@inheritdoc}
  66.      */
  67.     public function handle(Request $request$type HttpKernelInterface::MASTER_REQUEST$catch true)
  68.     {
  69.         $request->headers->set('X-Php-Ob-Level', (string) ob_get_level());
  70.         $this->requestStack->push($request);
  71.         try {
  72.             return $this->handleRaw($request$type);
  73.         } catch (\Exception $e) {
  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.     /**
  87.      * {@inheritdoc}
  88.      */
  89.     public function terminate(Request $requestResponse $response)
  90.     {
  91.         $this->dispatcher->dispatch(new TerminateEvent($this$request$response), KernelEvents::TERMINATE);
  92.     }
  93.     /**
  94.      * @internal
  95.      */
  96.     public function terminateWithException(\Throwable $exceptionRequest $request null)
  97.     {
  98.         if (!$request $request ?: $this->requestStack->getMasterRequest()) {
  99.             throw $exception;
  100.         }
  101.         $response $this->handleThrowable($exception$requestself::MASTER_REQUEST);
  102.         $response->sendHeaders();
  103.         $response->sendContent();
  104.         $this->terminate($request$response);
  105.     }
  106.     /**
  107.      * Handles a request to convert it to a response.
  108.      *
  109.      * Exceptions are not caught.
  110.      *
  111.      * @throws \LogicException       If one of the listener does not behave as expected
  112.      * @throws NotFoundHttpException When controller cannot be found
  113.      */
  114.     private function handleRaw(Request $requestint $type self::MASTER_REQUEST): Response
  115.     {
  116.         // request
  117.         $event = new RequestEvent($this$request$type);
  118.         $this->dispatcher->dispatch($eventKernelEvents::REQUEST);
  119.         if ($event->hasResponse()) {
  120.             return $this->filterResponse($event->getResponse(), $request$type);
  121.         }
  122.         // load controller
  123.         if (false === $controller $this->resolver->getController($request)) {
  124.             throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.'$request->getPathInfo()));
  125.         }
  126.         $event = new ControllerEvent($this$controller$request$type);
  127.         $this->dispatcher->dispatch($eventKernelEvents::CONTROLLER);
  128.         $controller $event->getController();
  129.         // controller arguments
  130.         $arguments $this->argumentResolver->getArguments($request$controller);
  131.         $event = new ControllerArgumentsEvent($this$controller$arguments$request$type);
  132.         $this->dispatcher->dispatch($eventKernelEvents::CONTROLLER_ARGUMENTS);
  133.         $controller $event->getController();
  134.         $arguments $event->getArguments();
  135.         // call controller
  136.         $response $controller(...$arguments);
  137.         // view
  138.         if (!$response instanceof Response) {
  139.             $event = new ViewEvent($this$request$type$response);
  140.             $this->dispatcher->dispatch($eventKernelEvents::VIEW);
  141.             if ($event->hasResponse()) {
  142.                 $response $event->getResponse();
  143.             } else {
  144.                 $msg sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.'$this->varToString($response));
  145.                 // the user may have forgotten to return something
  146.                 if (null === $response) {
  147.                     $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  148.                 }
  149.                 throw new ControllerDoesNotReturnResponseException($msg$controller__FILE____LINE__ 17);
  150.             }
  151.         }
  152.         return $this->filterResponse($response$request$type);
  153.     }
  154.     /**
  155.      * Filters a response object.
  156.      *
  157.      * @throws \RuntimeException if the passed object is not a Response instance
  158.      */
  159.     private function filterResponse(Response $responseRequest $requestint $type): Response
  160.     {
  161.         $event = new ResponseEvent($this$request$type$response);
  162.         $this->dispatcher->dispatch($eventKernelEvents::RESPONSE);
  163.         $this->finishRequest($request$type);
  164.         return $event->getResponse();
  165.     }
  166.     /**
  167.      * Publishes the finish request event, then pop the request from the stack.
  168.      *
  169.      * Note that the order of the operations is important here, otherwise
  170.      * operations such as {@link RequestStack::getParentRequest()} can lead to
  171.      * weird results.
  172.      */
  173.     private function finishRequest(Request $requestint $type)
  174.     {
  175.         $this->dispatcher->dispatch(new FinishRequestEvent($this$request$type), KernelEvents::FINISH_REQUEST);
  176.     }
  177.     /**
  178.      * Handles a throwable by trying to convert it to a Response.
  179.      *
  180.      * @throws \Exception
  181.      */
  182.     private function handleThrowable(\Throwable $eRequest $requestint $type): Response
  183.     {
  184.         $event = new ExceptionEvent($this$request$type$e);
  185.         $this->dispatcher->dispatch($eventKernelEvents::EXCEPTION);
  186.         // a listener might have replaced the exception
  187.         $e $event->getThrowable();
  188.         if (!$event->hasResponse()) {
  189.             $this->finishRequest($request$type);
  190.             throw $e;
  191.         }
  192.         $response $event->getResponse();
  193.         // the developer asked for a specific status code
  194.         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  195.             // ensure that we actually have an error response
  196.             if ($e instanceof HttpExceptionInterface) {
  197.                 // keep the HTTP status code and headers
  198.                 $response->setStatusCode($e->getStatusCode());
  199.                 $response->headers->add($e->getHeaders());
  200.             } else {
  201.                 $response->setStatusCode(500);
  202.             }
  203.         }
  204.         try {
  205.             return $this->filterResponse($response$request$type);
  206.         } catch (\Exception $e) {
  207.             return $response;
  208.         }
  209.     }
  210.     /**
  211.      * Returns a human-readable string for the specified variable.
  212.      */
  213.     private function varToString($var): string
  214.     {
  215.         if (\is_object($var)) {
  216.             return sprintf('an object of type %s', \get_class($var));
  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. }