3c46be860810f3ec2012491c73dbde97680ac464
[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  * @author Fabien Potencier <fabien@symfony.com>
34  */
35 class RouterListener implements EventSubscriberInterface
36 {
37     private $matcher;
38     private $context;
39     private $logger;
40     private $requestStack;
41
42     /**
43      * Constructor.
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      *
50      * @throws \InvalidArgumentException
51      */
52     public function __construct($matcher, RequestStack $requestStack, RequestContext $context = null, LoggerInterface $logger = null)
53     {
54         if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
55             throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
56         }
57
58         if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
59             throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
60         }
61
62         $this->matcher = $matcher;
63         $this->context = $context ?: $matcher->getContext();
64         $this->requestStack = $requestStack;
65         $this->logger = $logger;
66     }
67
68     private function setCurrentRequest(Request $request = null)
69     {
70         if (null !== $request) {
71             $this->context->fromRequest($request);
72         }
73     }
74
75     /**
76      * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
77      * operates on the correct context again.
78      *
79      * @param FinishRequestEvent $event
80      */
81     public function onKernelFinishRequest(FinishRequestEvent $event)
82     {
83         $this->setCurrentRequest($this->requestStack->getParentRequest());
84     }
85
86     public function onKernelRequest(GetResponseEvent $event)
87     {
88         $request = $event->getRequest();
89
90         $this->setCurrentRequest($request);
91
92         if ($request->attributes->has('_controller')) {
93             // routing is already done
94             return;
95         }
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
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
115             $request->attributes->add($parameters);
116             unset($parameters['_route'], $parameters['_controller']);
117             $request->attributes->set('_route_params', $parameters);
118         } catch (ResourceNotFoundException $e) {
119             $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
120
121             if ($referer = $request->headers->get('referer')) {
122                 $message .= sprintf(' (from "%s")', $referer);
123             }
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
129             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
130         }
131     }
132
133     public static function getSubscribedEvents()
134     {
135         return array(
136             KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
137             KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
138         );
139     }
140 }