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

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\BadRequestHttpException;
  18. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  19. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  20. use Symfony\Component\HttpFoundation\RequestStack;
  21. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  22. use Symfony\Component\Routing\Exception\NoConfigurationException;
  23. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  24. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  25. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  26. use Symfony\Component\Routing\RequestContext;
  27. use Symfony\Component\Routing\RequestContextAwareInterface;
  28. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  29. use Symfony\Component\HttpFoundation\Request;
  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. class RouterListener implements EventSubscriberInterface
  37. {
  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.     {
  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.      * @param FinishRequestEvent $event
  84.      */
  85.     public function onKernelFinishRequest(FinishRequestEvent $event)
  86.     {
  87.         $this->setCurrentRequest($this->requestStack->getParentRequest());
  88.     }
  89.     public function onKernelRequest(GetResponseEvent $event)
  90.     {
  91.         $request $event->getRequest();
  92.         $this->setCurrentRequest($request);
  93.         if ($request->attributes->has('_controller')) {
  94.             // routing is already done
  95.             return;
  96.         }
  97.         // add attributes based on the request (routing)
  98.         try {
  99.             // matching a request is more powerful than matching a URL path + context, so try that first
  100.             if ($this->matcher instanceof RequestMatcherInterface) {
  101.                 $parameters $this->matcher->matchRequest($request);
  102.             } else {
  103.                 $parameters $this->matcher->match($request->getPathInfo());
  104.             }
  105.             if (null !== $this->logger) {
  106.                 $this->logger->info('Matched route "{route}".', array(
  107.                     'route' => isset($parameters['_route']) ? $parameters['_route'] : 'n/a',
  108.                     'route_parameters' => $parameters,
  109.                     'request_uri' => $request->getUri(),
  110.                     'method' => $request->getMethod(),
  111.                 ));
  112.             }
  113.             $request->attributes->add($parameters);
  114.             unset($parameters['_route'], $parameters['_controller']);
  115.             $request->attributes->set('_route_params'$parameters);
  116.         } catch (ResourceNotFoundException $e) {
  117.             if ($this->debug && $e instanceof NoConfigurationException) {
  118.                 $event->setResponse($this->createWelcomeResponse());
  119.                 return;
  120.             }
  121.             $message sprintf('No route found for "%s %s"'$request->getMethod(), $request->getPathInfo());
  122.             if ($referer $request->headers->get('referer')) {
  123.                 $message .= sprintf(' (from "%s")'$referer);
  124.             }
  125.             throw new NotFoundHttpException($message$e);
  126.         } catch (MethodNotAllowedException $e) {
  127.             $message sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)'$request->getMethod(), $request->getPathInfo(), implode(', '$e->getAllowedMethods()));
  128.             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message$e);
  129.         }
  130.     }
  131.     public static function getSubscribedEvents()
  132.     {
  133.         return array(
  134.             KernelEvents::REQUEST => array(array('onKernelRequest'32)),
  135.             KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest'0)),
  136.         );
  137.     }
  138.     private function createWelcomeResponse()
  139.     {
  140.         $version Kernel::VERSION;
  141.         $baseDir realpath($this->projectDir).DIRECTORY_SEPARATOR;
  142.         $docVersion substr(Kernel::VERSION03);
  143.         ob_start();
  144.         include __DIR__.'/../Resources/welcome.html.php';
  145.         return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);
  146.     }
  147. }