Version 1
[yaffs-website] / vendor / symfony / http-kernel / EventListener / RouterListener.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\HttpKernel\EventListener;
13
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;
29
30 /**
31  * Initializes the context from the request and sets request attributes based on a matching route.
32  *
33  * This listener works in 2 modes:
34  *
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.
37  *
38  * @author Fabien Potencier <fabien@symfony.com>
39  */
40 class RouterListener implements EventSubscriberInterface
41 {
42     private $matcher;
43     private $context;
44     private $logger;
45     private $request;
46     private $requestStack;
47
48     /**
49      * Constructor.
50      *
51      * RequestStack will become required in 3.0.
52      *
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
57      *
58      * @throws \InvalidArgumentException
59      */
60     public function __construct($matcher, $requestStack = null, $context = null, $logger = null)
61     {
62         if ($requestStack instanceof RequestContext || $context instanceof LoggerInterface || $logger instanceof RequestStack) {
63             $tmp = $requestStack;
64             $requestStack = $logger;
65             $logger = $context;
66             $context = $tmp;
67
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);
71         }
72
73         if (null !== $requestStack && !$requestStack instanceof RequestStack) {
74             throw new \InvalidArgumentException('RequestStack instance expected.');
75         }
76         if (null !== $context && !$context instanceof RequestContext) {
77             throw new \InvalidArgumentException('RequestContext instance expected.');
78         }
79         if (null !== $logger && !$logger instanceof LoggerInterface) {
80             throw new \InvalidArgumentException('Logger must implement LoggerInterface.');
81         }
82
83         if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
84             throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
85         }
86
87         if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
88             throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
89         }
90
91         $this->matcher = $matcher;
92         $this->context = $context ?: $matcher->getContext();
93         $this->requestStack = $requestStack;
94         $this->logger = $logger;
95     }
96
97     /**
98      * Sets the current Request.
99      *
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.
103      *
104      * @param Request|null $request A Request instance
105      *
106      * @deprecated since version 2.4, to be removed in 3.0.
107      */
108     public function setRequest(Request $request = null)
109     {
110         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be made private in 3.0.', E_USER_DEPRECATED);
111
112         $this->setCurrentRequest($request);
113     }
114
115     private function setCurrentRequest(Request $request = null)
116     {
117         if (null !== $request && $this->request !== $request) {
118             $this->context->fromRequest($request);
119         }
120
121         $this->request = $request;
122     }
123
124     public function onKernelFinishRequest(FinishRequestEvent $event)
125     {
126         if (null === $this->requestStack) {
127             return; // removed when requestStack is required
128         }
129
130         $this->setCurrentRequest($this->requestStack->getParentRequest());
131     }
132
133     public function onKernelRequest(GetResponseEvent $event)
134     {
135         $request = $event->getRequest();
136
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);
143         }
144
145         if ($request->attributes->has('_controller')) {
146             // routing is already done
147             return;
148         }
149
150         // add attributes based on the request (routing)
151         try {
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);
155             } else {
156                 $parameters = $this->matcher->match($request->getPathInfo());
157             }
158
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(),
163                 ));
164             }
165
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());
171
172             if ($referer = $request->headers->get('referer')) {
173                 $message .= sprintf(' (from "%s")', $referer);
174             }
175
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()));
179
180             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
181         }
182     }
183
184     public static function getSubscribedEvents()
185     {
186         return array(
187             KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
188             KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
189         );
190     }
191 }