vendor/symfony/http-kernel/EventListener/RouterListener.php line 114

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\EventListener;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  17. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  18. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  19. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  20. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  21. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  22. use Symfony\Component\HttpKernel\Kernel;
  23. use Symfony\Component\HttpKernel\KernelEvents;
  24. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  25. use Symfony\Component\Routing\Exception\NoConfigurationException;
  26. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  27. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  28. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  29. use Symfony\Component\Routing\RequestContext;
  30. use Symfony\Component\Routing\RequestContextAwareInterface;
  31. /**
  32.  * Initializes the context from the request and sets request attributes based on a matching route.
  33.  *
  34.  * @author Fabien Potencier <fabien@symfony.com>
  35.  * @author Yonel Ceruto <yonelceruto@gmail.com>
  36.  *
  37.  * @final since Symfony 4.3
  38.  */
  39. class RouterListener implements EventSubscriberInterface
  40. {
  41.     private $matcher;
  42.     private $context;
  43.     private $logger;
  44.     private $requestStack;
  45.     private $projectDir;
  46.     private $debug;
  47.     /**
  48.      * @param UrlMatcherInterface|RequestMatcherInterface $matcher      The Url or Request matcher
  49.      * @param RequestStack                                $requestStack A RequestStack instance
  50.      * @param RequestContext|null                         $context      The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
  51.      * @param LoggerInterface|null                        $logger       The logger
  52.      * @param string                                      $projectDir
  53.      *
  54.      * @throws \InvalidArgumentException
  55.      */
  56.     public function __construct($matcherRequestStack $requestStackRequestContext $context nullLoggerInterface $logger nullstring $projectDir nullbool $debug true)
  57.     {
  58.         if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
  59.             throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
  60.         }
  61.         if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
  62.             throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
  63.         }
  64.         $this->matcher $matcher;
  65.         $this->context $context ?: $matcher->getContext();
  66.         $this->requestStack $requestStack;
  67.         $this->logger $logger;
  68.         $this->projectDir $projectDir;
  69.         $this->debug $debug;
  70.     }
  71.     private function setCurrentRequest(Request $request null)
  72.     {
  73.         if (null !== $request) {
  74.             try {
  75.                 $this->context->fromRequest($request);
  76.             } catch (\UnexpectedValueException $e) {
  77.                 throw new BadRequestHttpException($e->getMessage(), $e$e->getCode());
  78.             }
  79.         }
  80.     }
  81.     /**
  82.      * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
  83.      * operates on the correct context again.
  84.      */
  85.     public function onKernelFinishRequest(FinishRequestEvent $event)
  86.     {
  87.         $this->setCurrentRequest($this->requestStack->getParentRequest());
  88.     }
  89.     public function onKernelRequest(GetResponseEvent $event)
  90.     {
  91.         $request $event->getRequest();
  92.         $this->setCurrentRequest($request);
  93.         if ($request->attributes->has('_controller')) {
  94.             // routing is already done
  95.             return;
  96.         }
  97.         // add attributes based on the request (routing)
  98.         try {
  99.             // matching a request is more powerful than matching a URL path + context, so try that first
  100.             if ($this->matcher instanceof RequestMatcherInterface) {
  101.                 $parameters $this->matcher->matchRequest($request);
  102.             } else {
  103.                 $parameters $this->matcher->match($request->getPathInfo());
  104.             }
  105.             if (null !== $this->logger) {
  106.                 $this->logger->info('Matched route "{route}".', [
  107.                     'route' => isset($parameters['_route']) ? $parameters['_route'] : 'n/a',
  108.                     'route_parameters' => $parameters,
  109.                     'request_uri' => $request->getUri(),
  110.                     'method' => $request->getMethod(),
  111.                 ]);
  112.             }
  113.             $request->attributes->add($parameters);
  114.             unset($parameters['_route'], $parameters['_controller']);
  115.             $request->attributes->set('_route_params'$parameters);
  116.         } catch (ResourceNotFoundException $e) {
  117.             $message sprintf('No route found for "%s %s"'$request->getMethod(), $request->getPathInfo());
  118.             if ($referer $request->headers->get('referer')) {
  119.                 $message .= sprintf(' (from "%s")'$referer);
  120.             }
  121.             throw new NotFoundHttpException($message$e);
  122.         } catch (MethodNotAllowedException $e) {
  123.             $message sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)'$request->getMethod(), $request->getPathInfo(), implode(', '$e->getAllowedMethods()));
  124.             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message$e);
  125.         }
  126.     }
  127.     public function onKernelException(GetResponseForExceptionEvent $event)
  128.     {
  129.         if (!$this->debug || !($e $event->getException()) instanceof NotFoundHttpException) {
  130.             return;
  131.         }
  132.         if ($e->getPrevious() instanceof NoConfigurationException) {
  133.             $event->setResponse($this->createWelcomeResponse());
  134.         }
  135.     }
  136.     public static function getSubscribedEvents()
  137.     {
  138.         return [
  139.             KernelEvents::REQUEST => [['onKernelRequest'32]],
  140.             KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest'0]],
  141.             KernelEvents::EXCEPTION => ['onKernelException', -64],
  142.         ];
  143.     }
  144.     private function createWelcomeResponse()
  145.     {
  146.         $version Kernel::VERSION;
  147.         $baseDir realpath($this->projectDir).\DIRECTORY_SEPARATOR;
  148.         $docVersion substr(Kernel::VERSION03);
  149.         ob_start();
  150.         include __DIR__.'/../Resources/welcome.html.php';
  151.         return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);
  152.     }
  153. }