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

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