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

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