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\HttpKernel\Event\GetResponseEvent;
16 use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
17 use Symfony\Component\HttpKernel\KernelEvents;
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\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;
31 * Initializes the context from the request and sets request attributes based on a matching route.
33 * This listener works in 2 modes:
35 * * 2.3 compatibility mode where you must call setRequest whenever the Request changes.
36 * * 2.4+ mode where you must pass a RequestStack instance in the constructor.
38 * @author Fabien Potencier <fabien@symfony.com>
40 class RouterListener implements EventSubscriberInterface
46 private $requestStack;
51 * RequestStack will become required in 3.0.
53 * @param UrlMatcherInterface|RequestMatcherInterface $matcher The Url or Request matcher
54 * @param RequestStack $requestStack A RequestStack instance
55 * @param RequestContext|null $context The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
56 * @param LoggerInterface|null $logger The logger
58 * @throws \InvalidArgumentException
60 public function __construct($matcher, $requestStack = null, $context = null, $logger = null)
62 if ($requestStack instanceof RequestContext || $context instanceof LoggerInterface || $logger instanceof RequestStack) {
64 $requestStack = $logger;
68 @trigger_error('The '.__METHOD__.' method now requires a RequestStack to be given as second argument as '.__CLASS__.'::setRequest method will not be supported anymore in 3.0.', E_USER_DEPRECATED);
69 } elseif (!$requestStack instanceof RequestStack) {
70 @trigger_error('The '.__METHOD__.' method now requires a RequestStack instance as '.__CLASS__.'::setRequest method will not be supported anymore in 3.0.', E_USER_DEPRECATED);
73 if (null !== $requestStack && !$requestStack instanceof RequestStack) {
74 throw new \InvalidArgumentException('RequestStack instance expected.');
76 if (null !== $context && !$context instanceof RequestContext) {
77 throw new \InvalidArgumentException('RequestContext instance expected.');
79 if (null !== $logger && !$logger instanceof LoggerInterface) {
80 throw new \InvalidArgumentException('Logger must implement LoggerInterface.');
83 if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
84 throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
87 if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
88 throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
91 $this->matcher = $matcher;
92 $this->context = $context ?: $matcher->getContext();
93 $this->requestStack = $requestStack;
94 $this->logger = $logger;
98 * Sets the current Request.
100 * This method was used to synchronize the Request, but as the HttpKernel
101 * is doing that automatically now, you should never call it directly.
102 * It is kept public for BC with the 2.3 version.
104 * @param Request|null $request A Request instance
106 * @deprecated since version 2.4, to be removed in 3.0.
108 public function setRequest(Request $request = null)
110 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be made private in 3.0.', E_USER_DEPRECATED);
112 $this->setCurrentRequest($request);
115 private function setCurrentRequest(Request $request = null)
117 if (null !== $request && $this->request !== $request) {
118 $this->context->fromRequest($request);
121 $this->request = $request;
124 public function onKernelFinishRequest(FinishRequestEvent $event)
126 if (null === $this->requestStack) {
127 return; // removed when requestStack is required
130 $this->setCurrentRequest($this->requestStack->getParentRequest());
133 public function onKernelRequest(GetResponseEvent $event)
135 $request = $event->getRequest();
137 // initialize the context that is also used by the generator (assuming matcher and generator share the same context instance)
138 // we call setCurrentRequest even if most of the time, it has already been done to keep compatibility
139 // with frameworks which do not use the Symfony service container
140 // when we have a RequestStack, no need to do it
141 if (null !== $this->requestStack) {
142 $this->setCurrentRequest($request);
145 if ($request->attributes->has('_controller')) {
146 // routing is already done
150 // add attributes based on the request (routing)
152 // matching a request is more powerful than matching a URL path + context, so try that first
153 if ($this->matcher instanceof RequestMatcherInterface) {
154 $parameters = $this->matcher->matchRequest($request);
156 $parameters = $this->matcher->match($request->getPathInfo());
159 if (null !== $this->logger) {
160 $this->logger->info(sprintf('Matched route "%s".', isset($parameters['_route']) ? $parameters['_route'] : 'n/a'), array(
161 'route_parameters' => $parameters,
162 'request_uri' => $request->getUri(),
166 $request->attributes->add($parameters);
167 unset($parameters['_route'], $parameters['_controller']);
168 $request->attributes->set('_route_params', $parameters);
169 } catch (ResourceNotFoundException $e) {
170 $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
172 if ($referer = $request->headers->get('referer')) {
173 $message .= sprintf(' (from "%s")', $referer);
176 throw new NotFoundHttpException($message, $e);
177 } catch (MethodNotAllowedException $e) {
178 $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), implode(', ', $e->getAllowedMethods()));
180 throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
184 public static function getSubscribedEvents()
187 KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
188 KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),