4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\EventListener;
14 use Psr\Log\LoggerInterface;
15 use Symfony\Component\HttpFoundation\Response;
16 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
17 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
18 use Symfony\Component\HttpKernel\Kernel;
19 use Symfony\Component\HttpKernel\KernelEvents;
20 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
21 use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
22 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
23 use Symfony\Component\HttpFoundation\RequestStack;
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\UrlMatcherInterface;
28 use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
29 use Symfony\Component\Routing\RequestContext;
30 use Symfony\Component\Routing\RequestContextAwareInterface;
31 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
32 use Symfony\Component\HttpFoundation\Request;
35 * Initializes the context from the request and sets request attributes based on a matching route.
37 * @author Fabien Potencier <fabien@symfony.com>
38 * @author Yonel Ceruto <yonelceruto@gmail.com>
40 class RouterListener implements EventSubscriberInterface
45 private $requestStack;
50 * @param UrlMatcherInterface|RequestMatcherInterface $matcher The Url or Request matcher
51 * @param RequestStack $requestStack A RequestStack instance
52 * @param RequestContext|null $context The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
53 * @param LoggerInterface|null $logger The logger
54 * @param string $projectDir
57 * @throws \InvalidArgumentException
59 public function __construct($matcher, RequestStack $requestStack, RequestContext $context = null, LoggerInterface $logger = null, $projectDir = null, $debug = true)
61 if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
62 throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
65 if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
66 throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
69 $this->matcher = $matcher;
70 $this->context = $context ?: $matcher->getContext();
71 $this->requestStack = $requestStack;
72 $this->logger = $logger;
73 $this->projectDir = $projectDir;
74 $this->debug = $debug;
77 private function setCurrentRequest(Request $request = null)
79 if (null !== $request) {
81 $this->context->fromRequest($request);
82 } catch (\UnexpectedValueException $e) {
83 throw new BadRequestHttpException($e->getMessage(), $e, $e->getCode());
89 * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
90 * operates on the correct context again.
92 * @param FinishRequestEvent $event
94 public function onKernelFinishRequest(FinishRequestEvent $event)
96 $this->setCurrentRequest($this->requestStack->getParentRequest());
99 public function onKernelRequest(GetResponseEvent $event)
101 $request = $event->getRequest();
103 $this->setCurrentRequest($request);
105 if ($request->attributes->has('_controller')) {
106 // routing is already done
110 // add attributes based on the request (routing)
112 // matching a request is more powerful than matching a URL path + context, so try that first
113 if ($this->matcher instanceof RequestMatcherInterface) {
114 $parameters = $this->matcher->matchRequest($request);
116 $parameters = $this->matcher->match($request->getPathInfo());
119 if (null !== $this->logger) {
120 $this->logger->info('Matched route "{route}".', array(
121 'route' => isset($parameters['_route']) ? $parameters['_route'] : 'n/a',
122 'route_parameters' => $parameters,
123 'request_uri' => $request->getUri(),
124 'method' => $request->getMethod(),
128 $request->attributes->add($parameters);
129 unset($parameters['_route'], $parameters['_controller']);
130 $request->attributes->set('_route_params', $parameters);
131 } catch (ResourceNotFoundException $e) {
132 if ($this->debug && $e instanceof NoConfigurationException) {
133 $event->setResponse($this->createWelcomeResponse());
138 $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
140 if ($referer = $request->headers->get('referer')) {
141 $message .= sprintf(' (from "%s")', $referer);
144 throw new NotFoundHttpException($message, $e);
145 } catch (MethodNotAllowedException $e) {
146 $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), implode(', ', $e->getAllowedMethods()));
148 throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
152 public static function getSubscribedEvents()
155 KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
156 KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
160 private function createWelcomeResponse()
162 $version = Kernel::VERSION;
163 $baseDir = realpath($this->projectDir).DIRECTORY_SEPARATOR;
164 $docVersion = substr(Kernel::VERSION, 0, 3);
167 include __DIR__.'/../Resources/welcome.html.php';
169 return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);