Updated to Drupal 8.5. Core Media not yet in use.
[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\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;
33
34 /**
35  * Initializes the context from the request and sets request attributes based on a matching route.
36  *
37  * @author Fabien Potencier <fabien@symfony.com>
38  * @author Yonel Ceruto <yonelceruto@gmail.com>
39  */
40 class RouterListener implements EventSubscriberInterface
41 {
42     private $matcher;
43     private $context;
44     private $logger;
45     private $requestStack;
46     private $projectDir;
47     private $debug;
48
49     /**
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
55      * @param bool                                        $debug
56      *
57      * @throws \InvalidArgumentException
58      */
59     public function __construct($matcher, RequestStack $requestStack, RequestContext $context = null, LoggerInterface $logger = null, $projectDir = null, $debug = true)
60     {
61         if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
62             throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
63         }
64
65         if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
66             throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
67         }
68
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;
75     }
76
77     private function setCurrentRequest(Request $request = null)
78     {
79         if (null !== $request) {
80             try {
81                 $this->context->fromRequest($request);
82             } catch (\UnexpectedValueException $e) {
83                 throw new BadRequestHttpException($e->getMessage(), $e, $e->getCode());
84             }
85         }
86     }
87
88     /**
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.
91      *
92      * @param FinishRequestEvent $event
93      */
94     public function onKernelFinishRequest(FinishRequestEvent $event)
95     {
96         $this->setCurrentRequest($this->requestStack->getParentRequest());
97     }
98
99     public function onKernelRequest(GetResponseEvent $event)
100     {
101         $request = $event->getRequest();
102
103         $this->setCurrentRequest($request);
104
105         if ($request->attributes->has('_controller')) {
106             // routing is already done
107             return;
108         }
109
110         // add attributes based on the request (routing)
111         try {
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);
115             } else {
116                 $parameters = $this->matcher->match($request->getPathInfo());
117             }
118
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(),
125                 ));
126             }
127
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());
134
135                 return;
136             }
137
138             $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
139
140             if ($referer = $request->headers->get('referer')) {
141                 $message .= sprintf(' (from "%s")', $referer);
142             }
143
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()));
147
148             throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
149         }
150     }
151
152     public static function getSubscribedEvents()
153     {
154         return array(
155             KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
156             KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
157         );
158     }
159
160     private function createWelcomeResponse()
161     {
162         $version = Kernel::VERSION;
163         $baseDir = realpath($this->projectDir).DIRECTORY_SEPARATOR;
164         $docVersion = substr(Kernel::VERSION, 0, 3);
165
166         ob_start();
167         include __DIR__.'/../Resources/welcome.html.php';
168
169         return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);
170     }
171 }