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

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