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

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