445cfc4e87102f408ea7206e110277caeb0e5f40
[yaffs-website] / vendor / symfony / routing / Matcher / UrlMatcher.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\Routing\Matcher;
13
14 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
15 use Symfony\Component\Routing\Exception\NoConfigurationException;
16 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
17 use Symfony\Component\Routing\RouteCollection;
18 use Symfony\Component\Routing\RequestContext;
19 use Symfony\Component\Routing\Route;
20 use Symfony\Component\HttpFoundation\Request;
21 use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
22 use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
23
24 /**
25  * UrlMatcher matches URL based on a set of routes.
26  *
27  * @author Fabien Potencier <fabien@symfony.com>
28  */
29 class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
30 {
31     const REQUIREMENT_MATCH = 0;
32     const REQUIREMENT_MISMATCH = 1;
33     const ROUTE_MATCH = 2;
34
35     protected $context;
36     protected $allow = array();
37     protected $routes;
38     protected $request;
39     protected $expressionLanguage;
40
41     /**
42      * @var ExpressionFunctionProviderInterface[]
43      */
44     protected $expressionLanguageProviders = array();
45
46     public function __construct(RouteCollection $routes, RequestContext $context)
47     {
48         $this->routes = $routes;
49         $this->context = $context;
50     }
51
52     /**
53      * {@inheritdoc}
54      */
55     public function setContext(RequestContext $context)
56     {
57         $this->context = $context;
58     }
59
60     /**
61      * {@inheritdoc}
62      */
63     public function getContext()
64     {
65         return $this->context;
66     }
67
68     /**
69      * {@inheritdoc}
70      */
71     public function match($pathinfo)
72     {
73         $this->allow = array();
74
75         if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
76             return $ret;
77         }
78
79         if ('/' === $pathinfo && !$this->allow) {
80             throw new NoConfigurationException();
81         }
82
83         throw 0 < count($this->allow)
84             ? new MethodNotAllowedException(array_unique($this->allow))
85             : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
86     }
87
88     /**
89      * {@inheritdoc}
90      */
91     public function matchRequest(Request $request)
92     {
93         $this->request = $request;
94
95         $ret = $this->match($request->getPathInfo());
96
97         $this->request = null;
98
99         return $ret;
100     }
101
102     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
103     {
104         $this->expressionLanguageProviders[] = $provider;
105     }
106
107     /**
108      * Tries to match a URL with a set of routes.
109      *
110      * @param string          $pathinfo The path info to be parsed
111      * @param RouteCollection $routes   The set of routes
112      *
113      * @return array An array of parameters
114      *
115      * @throws NoConfigurationException  If no routing configuration could be found
116      * @throws ResourceNotFoundException If the resource could not be found
117      * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
118      */
119     protected function matchCollection($pathinfo, RouteCollection $routes)
120     {
121         foreach ($routes as $name => $route) {
122             $compiledRoute = $route->compile();
123
124             // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
125             if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
126                 continue;
127             }
128
129             if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
130                 continue;
131             }
132
133             $hostMatches = array();
134             if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
135                 continue;
136             }
137
138             $status = $this->handleRouteRequirements($pathinfo, $name, $route);
139
140             if (self::REQUIREMENT_MISMATCH === $status[0]) {
141                 continue;
142             }
143
144             // check HTTP method requirement
145             if ($requiredMethods = $route->getMethods()) {
146                 // HEAD and GET are equivalent as per RFC
147                 if ('HEAD' === $method = $this->context->getMethod()) {
148                     $method = 'GET';
149                 }
150
151                 if (!in_array($method, $requiredMethods)) {
152                     if (self::REQUIREMENT_MATCH === $status[0]) {
153                         $this->allow = array_merge($this->allow, $requiredMethods);
154                     }
155
156                     continue;
157                 }
158             }
159
160             return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, isset($status[1]) ? $status[1] : array()));
161         }
162     }
163
164     /**
165      * Returns an array of values to use as request attributes.
166      *
167      * As this method requires the Route object, it is not available
168      * in matchers that do not have access to the matched Route instance
169      * (like the PHP and Apache matcher dumpers).
170      *
171      * @param Route  $route      The route we are matching against
172      * @param string $name       The name of the route
173      * @param array  $attributes An array of attributes from the matcher
174      *
175      * @return array An array of parameters
176      */
177     protected function getAttributes(Route $route, $name, array $attributes)
178     {
179         $attributes['_route'] = $name;
180
181         return $this->mergeDefaults($attributes, $route->getDefaults());
182     }
183
184     /**
185      * Handles specific route requirements.
186      *
187      * @param string $pathinfo The path
188      * @param string $name     The route name
189      * @param Route  $route    The route
190      *
191      * @return array The first element represents the status, the second contains additional information
192      */
193     protected function handleRouteRequirements($pathinfo, $name, Route $route)
194     {
195         // expression condition
196         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) {
197             return array(self::REQUIREMENT_MISMATCH, null);
198         }
199
200         // check HTTP scheme requirement
201         $scheme = $this->context->getScheme();
202         $status = $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
203
204         return array($status, null);
205     }
206
207     /**
208      * Get merged default parameters.
209      *
210      * @param array $params   The parameters
211      * @param array $defaults The defaults
212      *
213      * @return array Merged default parameters
214      */
215     protected function mergeDefaults($params, $defaults)
216     {
217         foreach ($params as $key => $value) {
218             if (!is_int($key)) {
219                 $defaults[$key] = $value;
220             }
221         }
222
223         return $defaults;
224     }
225
226     protected function getExpressionLanguage()
227     {
228         if (null === $this->expressionLanguage) {
229             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
230                 throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
231             }
232             $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
233         }
234
235         return $this->expressionLanguage;
236     }
237
238     /**
239      * @internal
240      */
241     protected function createRequest($pathinfo)
242     {
243         if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
244             return null;
245         }
246
247         return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
248             'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
249             'SCRIPT_NAME' => $this->context->getBaseUrl(),
250         ));
251     }
252 }