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

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\ExceptionEvent;
  17. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  18. use Symfony\Component\HttpKernel\Event\RequestEvent;
  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
  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 RequestContext|null                         $context    The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
  50.      * @param string                                      $projectDir
  51.      *
  52.      * @throws \InvalidArgumentException
  53.      */
  54.     public function __construct($matcherRequestStack $requestStackRequestContext $context nullLoggerInterface $logger nullstring $projectDir nullbool $debug true)
  55.     {
  56.         if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
  57.             throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
  58.         }
  59.         if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
  60.             throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
  61.         }
  62.         $this->matcher $matcher;
  63.         $this->context $context ?: $matcher->getContext();
  64.         $this->requestStack $requestStack;
  65.         $this->logger $logger;
  66.         $this->projectDir $projectDir;
  67.         $this->debug $debug;
  68.     }
  69.     private function setCurrentRequest(Request $request null)
  70.     {
  71.         if (null !== $request) {
  72.             try {
  73.                 $this->context->fromRequest($request);
  74.             } catch (\UnexpectedValueException $e) {
  75.                 throw new BadRequestHttpException($e->getMessage(), $e$e->getCode());
  76.             }
  77.         }
  78.     }
  79.     /**
  80.      * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
  81.      * operates on the correct context again.
  82.      */
  83.     public function onKernelFinishRequest(FinishRequestEvent $event)
  84.     {
  85.         $this->setCurrentRequest($this->requestStack->getParentRequest());
  86.     }
  87.     public function onKernelRequest(RequestEvent $event)
  88.     {
  89.         $request $event->getRequest();
  90.         $this->setCurrentRequest($request);
  91.         if ($request->attributes->has('_controller')) {
  92.             // routing is already done
  93.             return;
  94.         }
  95.         // add attributes based on the request (routing)
  96.         try {
  97.             // matching a request is more powerful than matching a URL path + context, so try that first
  98.             if ($this->matcher instanceof RequestMatcherInterface) {
  99.                 $parameters $this->matcher->matchRequest($request);
  100.             } else {
  101.                 $parameters $this->matcher->match($request->getPathInfo());
  102.             }
  103.             if (null !== $this->logger) {
  104.                 $this->logger->info('Matched route "{route}".', [
  105.                     'route' => $parameters['_route'] ?? 'n/a',
  106.                     'route_parameters' => $parameters,
  107.                     'request_uri' => $request->getUri(),
  108.                     'method' => $request->getMethod(),
  109.                 ]);
  110.             }
  111.             $request->attributes->add($parameters);
  112.             unset($parameters['_route'], $parameters['_controller']);
  113.             $request->attributes->set('_route_params'$parameters);
  114.         } catch (ResourceNotFoundException $e) {
  115.             $message sprintf('No route found for "%s %s"'$request->getMethod(), $request->getUriForPath($request->getPathInfo()));
  116.             if ($referer $request->headers->get('referer')) {
  117.                 $message .= sprintf(' (from "%s")'$referer);
  118.             }
  119.             throw new NotFoundHttpException($message$e);
  120.         } catch (MethodNotAllowedException $e) {
  121.             $message sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)'$request->getMethod(), $request->getUriForPath($request->getPathInfo()), implode(', '$e->getAllowedMethods()));
  122.             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message$e);
  123.         }
  124.     }
  125.     public function onKernelException(ExceptionEvent $event)
  126.     {
  127.         if (!$this->debug || !($e $event->getThrowable()) instanceof NotFoundHttpException) {
  128.             return;
  129.         }
  130.         if ($e->getPrevious() instanceof NoConfigurationException) {
  131.             $event->setResponse($this->createWelcomeResponse());
  132.         }
  133.     }
  134.     public static function getSubscribedEvents(): array
  135.     {
  136.         return [
  137.             KernelEvents::REQUEST => [['onKernelRequest'32]],
  138.             KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest'0]],
  139.             KernelEvents::EXCEPTION => ['onKernelException', -64],
  140.         ];
  141.     }
  142.     private function createWelcomeResponse(): Response
  143.     {
  144.         $version Kernel::VERSION;
  145.         $projectDir realpath((string) $this->projectDir).\DIRECTORY_SEPARATOR;
  146.         $docVersion substr(Kernel::VERSION03);
  147.         ob_start();
  148.         include \dirname(__DIR__).'/Resources/welcome.html.php';
  149.         return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);
  150.     }
  151. }