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

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