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

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