vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php line 104

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\HttpKernel\Event\GetResponseEvent;
  13. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  16. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  17. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  18. use Symfony\Component\HttpFoundation\RequestStack;
  19. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  20. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  21. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  22. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  23. use Symfony\Component\Routing\RequestContext;
  24. use Symfony\Component\Routing\RequestContextAwareInterface;
  25. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  26. use Symfony\Component\HttpFoundation\Request;
  27. /**
  28.  * Initializes the context from the request and sets request attributes based on a matching route.
  29.  *
  30.  * @author Fabien Potencier <fabien@symfony.com>
  31.  */
  32. class RouterListener implements EventSubscriberInterface
  33. {
  34.     private $matcher;
  35.     private $context;
  36.     private $logger;
  37.     private $requestStack;
  38.     /**
  39.      * @param UrlMatcherInterface|RequestMatcherInterface $matcher      The Url or Request matcher
  40.      * @param RequestStack                                $requestStack A RequestStack instance
  41.      * @param RequestContext|null                         $context      The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
  42.      * @param LoggerInterface|null                        $logger       The logger
  43.      *
  44.      * @throws \InvalidArgumentException
  45.      */
  46.     public function __construct($matcherRequestStack $requestStackRequestContext $context nullLoggerInterface $logger null)
  47.     {
  48.         if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
  49.             throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
  50.         }
  51.         if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
  52.             throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
  53.         }
  54.         $this->matcher $matcher;
  55.         $this->context $context ?: $matcher->getContext();
  56.         $this->requestStack $requestStack;
  57.         $this->logger $logger;
  58.     }
  59.     private function setCurrentRequest(Request $request null)
  60.     {
  61.         if (null !== $request) {
  62.             try {
  63.                 $this->context->fromRequest($request);
  64.             } catch (\UnexpectedValueException $e) {
  65.                 throw new BadRequestHttpException($e->getMessage(), $e$e->getCode());
  66.             }
  67.         }
  68.     }
  69.     /**
  70.      * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
  71.      * operates on the correct context again.
  72.      *
  73.      * @param FinishRequestEvent $event
  74.      */
  75.     public function onKernelFinishRequest(FinishRequestEvent $event)
  76.     {
  77.         $this->setCurrentRequest($this->requestStack->getParentRequest());
  78.     }
  79.     public function onKernelRequest(GetResponseEvent $event)
  80.     {
  81.         $request $event->getRequest();
  82.         $this->setCurrentRequest($request);
  83.         if ($request->attributes->has('_controller')) {
  84.             // routing is already done
  85.             return;
  86.         }
  87.         // add attributes based on the request (routing)
  88.         try {
  89.             // matching a request is more powerful than matching a URL path + context, so try that first
  90.             if ($this->matcher instanceof RequestMatcherInterface) {
  91.                 $parameters $this->matcher->matchRequest($request);
  92.             } else {
  93.                 $parameters $this->matcher->match($request->getPathInfo());
  94.             }
  95.             if (null !== $this->logger) {
  96.                 $this->logger->info('Matched route "{route}".', array(
  97.                     'route' => isset($parameters['_route']) ? $parameters['_route'] : 'n/a',
  98.                     'route_parameters' => $parameters,
  99.                     'request_uri' => $request->getUri(),
  100.                     'method' => $request->getMethod(),
  101.                 ));
  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->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->getPathInfo(), implode(', '$e->getAllowedMethods()));
  114.             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message$e);
  115.         }
  116.     }
  117.     public static function getSubscribedEvents()
  118.     {
  119.         return array(
  120.             KernelEvents::REQUEST => array(array('onKernelRequest'32)),
  121.             KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest'0)),
  122.         );
  123.     }
  124. }