vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 151

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  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\HttpExceptionInterface;
  29. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  30. /**
  31.  * HttpKernel notifies events to convert a Request object to a Response one.
  32.  *
  33.  * @author Fabien Potencier <[email protected]>
  34.  */
  35. class HttpKernel implements HttpKernelInterfaceTerminableInterface
  36. {
  37.     protected $dispatcher;
  38.     protected $resolver;
  39.     protected $requestStack;
  40.     private $argumentResolver;
  41.     public function __construct(EventDispatcherInterface $dispatcherControllerResolverInterface $resolverRequestStack $requestStack nullArgumentResolverInterface $argumentResolver null)
  42.     {
  43.         $this->dispatcher $dispatcher;
  44.         $this->resolver $resolver;
  45.         $this->requestStack $requestStack ?: new RequestStack();
  46.         $this->argumentResolver $argumentResolver;
  47.         if (null === $this->argumentResolver) {
  48.             @trigger_error(sprintf('As of 3.1 an %s is used to resolve arguments. In 4.0 the $argumentResolver becomes the %s if no other is provided instead of using the $resolver argument.'ArgumentResolverInterface::class, ArgumentResolver::class), \E_USER_DEPRECATED);
  49.             // fallback in case of deprecations
  50.             $this->argumentResolver $resolver;
  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', (string) 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(KernelEvents::TERMINATE, new PostResponseEvent($this$request$response));
  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 $request$type self::MASTER_REQUEST)
  106.     {
  107.         $this->requestStack->push($request);
  108.         // request
  109.         $event = new GetResponseEvent($this$request$type);
  110.         $this->dispatcher->dispatch(KernelEvents::REQUEST$event);
  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 FilterControllerEvent($this$controller$request$type);
  119.         $this->dispatcher->dispatch(KernelEvents::CONTROLLER$event);
  120.         $controller $event->getController();
  121.         // controller arguments
  122.         $arguments $this->argumentResolver->getArguments($request$controller);
  123.         $event = new FilterControllerArgumentsEvent($this$controller$arguments$request$type);
  124.         $this->dispatcher->dispatch(KernelEvents::CONTROLLER_ARGUMENTS$event);
  125.         $controller $event->getController();
  126.         $arguments $event->getArguments();
  127.         // call controller
  128.         $response = \call_user_func_array($controller$arguments);
  129.         // view
  130.         if (!$response instanceof Response) {
  131.             $event = new GetResponseForControllerResultEvent($this$request$type$response);
  132.             $this->dispatcher->dispatch(KernelEvents::VIEW$event);
  133.             if ($event->hasResponse()) {
  134.                 $response $event->getResponse();
  135.             }
  136.             if (!$response instanceof Response) {
  137.                 $msg sprintf('The controller must return a response (%s given).'$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 \LogicException($msg);
  143.             }
  144.         }
  145.         return $this->filterResponse($response$request$type);
  146.     }
  147.     /**
  148.      * Filters a response object.
  149.      *
  150.      * @param Response $response A Response instance
  151.      * @param Request  $request  An error message in case the response is not a Response object
  152.      * @param int      $type     The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
  153.      *
  154.      * @return Response The filtered Response instance
  155.      *
  156.      * @throws \RuntimeException if the passed object is not a Response instance
  157.      */
  158.     private function filterResponse(Response $responseRequest $request$type)
  159.     {
  160.         $event = new FilterResponseEvent($this$request$type$response);
  161.         $this->dispatcher->dispatch(KernelEvents::RESPONSE$event);
  162.         $this->finishRequest($request$type);
  163.         return $event->getResponse();
  164.     }
  165.     /**
  166.      * Publishes the finish request event, then pop the request from the stack.
  167.      *
  168.      * Note that the order of the operations is important here, otherwise
  169.      * operations such as {@link RequestStack::getParentRequest()} can lead to
  170.      * weird results.
  171.      *
  172.      * @param int $type
  173.      */
  174.     private function finishRequest(Request $request$type)
  175.     {
  176.         $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this$request$type));
  177.         $this->requestStack->pop();
  178.     }
  179.     /**
  180.      * Handles an exception by trying to convert it to a Response.
  181.      *
  182.      * @param \Exception $e       An \Exception instance
  183.      * @param Request    $request A Request instance
  184.      * @param int        $type    The type of the request
  185.      *
  186.      * @return Response A Response instance
  187.      *
  188.      * @throws \Exception
  189.      */
  190.     private function handleException(\Exception $e$request$type)
  191.     {
  192.         $event = new GetResponseForExceptionEvent($this$request$type$e);
  193.         $this->dispatcher->dispatch(KernelEvents::EXCEPTION$event);
  194.         // a listener might have replaced the exception
  195.         $e $event->getException();
  196.         if (!$event->hasResponse()) {
  197.             $this->finishRequest($request$type);
  198.             throw $e;
  199.         }
  200.         $response $event->getResponse();
  201.         // the developer asked for a specific status code
  202.         if ($response->headers->has('X-Status-Code')) {
  203.             @trigger_error(sprintf('Using the X-Status-Code header is deprecated since Symfony 3.3 and will be removed in 4.0. Use %s::allowCustomResponseCode() instead.'GetResponseForExceptionEvent::class), \E_USER_DEPRECATED);
  204.             $response->setStatusCode($response->headers->get('X-Status-Code'));
  205.             $response->headers->remove('X-Status-Code');
  206.         } elseif (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
  207.             // ensure that we actually have an error response
  208.             if ($e instanceof HttpExceptionInterface) {
  209.                 // keep the HTTP status code and headers
  210.                 $response->setStatusCode($e->getStatusCode());
  211.                 $response->headers->add($e->getHeaders());
  212.             } else {
  213.                 $response->setStatusCode(500);
  214.             }
  215.         }
  216.         try {
  217.             return $this->filterResponse($response$request$type);
  218.         } catch (\Exception $e) {
  219.             return $response;
  220.         }
  221.     }
  222.     /**
  223.      * Returns a human-readable string for the specified variable.
  224.      */
  225.     private function varToString($var)
  226.     {
  227.         if (\is_object($var)) {
  228.             return sprintf('Object(%s)', \get_class($var));
  229.         }
  230.         if (\is_array($var)) {
  231.             $a = [];
  232.             foreach ($var as $k => $v) {
  233.                 $a[] = sprintf('%s => %s'$k$this->varToString($v));
  234.             }
  235.             return sprintf('Array(%s)'implode(', '$a));
  236.         }
  237.         if (\is_resource($var)) {
  238.             return sprintf('Resource(%s)'get_resource_type($var));
  239.         }
  240.         if (null === $var) {
  241.             return 'null';
  242.         }
  243.         if (false === $var) {
  244.             return 'false';
  245.         }
  246.         if (true === $var) {
  247.             return 'true';
  248.         }
  249.         return (string) $var;
  250.     }
  251. }