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\Routing\Matcher;
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;
25 * UrlMatcher matches URL based on a set of routes.
27 * @author Fabien Potencier <fabien@symfony.com>
29 class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
31 const REQUIREMENT_MATCH = 0;
32 const REQUIREMENT_MISMATCH = 1;
33 const ROUTE_MATCH = 2;
36 protected $allow = array();
39 protected $expressionLanguage;
42 * @var ExpressionFunctionProviderInterface[]
44 protected $expressionLanguageProviders = array();
46 public function __construct(RouteCollection $routes, RequestContext $context)
48 $this->routes = $routes;
49 $this->context = $context;
55 public function setContext(RequestContext $context)
57 $this->context = $context;
63 public function getContext()
65 return $this->context;
71 public function match($pathinfo)
73 $this->allow = array();
75 if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
79 if ('/' === $pathinfo && !$this->allow) {
80 throw new NoConfigurationException();
83 throw 0 < count($this->allow)
84 ? new MethodNotAllowedException(array_unique($this->allow))
85 : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
91 public function matchRequest(Request $request)
93 $this->request = $request;
95 $ret = $this->match($request->getPathInfo());
97 $this->request = null;
102 public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
104 $this->expressionLanguageProviders[] = $provider;
108 * Tries to match a URL with a set of routes.
110 * @param string $pathinfo The path info to be parsed
111 * @param RouteCollection $routes The set of routes
113 * @return array An array of parameters
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
119 protected function matchCollection($pathinfo, RouteCollection $routes)
121 foreach ($routes as $name => $route) {
122 $compiledRoute = $route->compile();
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())) {
129 if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
133 $hostMatches = array();
134 if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
138 $status = $this->handleRouteRequirements($pathinfo, $name, $route);
140 if (self::REQUIREMENT_MISMATCH === $status[0]) {
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()) {
151 if (!in_array($method, $requiredMethods)) {
152 if (self::REQUIREMENT_MATCH === $status[0]) {
153 $this->allow = array_merge($this->allow, $requiredMethods);
160 return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, isset($status[1]) ? $status[1] : array()));
165 * Returns an array of values to use as request attributes.
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).
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
175 * @return array An array of parameters
177 protected function getAttributes(Route $route, $name, array $attributes)
179 $attributes['_route'] = $name;
181 return $this->mergeDefaults($attributes, $route->getDefaults());
185 * Handles specific route requirements.
187 * @param string $pathinfo The path
188 * @param string $name The route name
189 * @param Route $route The route
191 * @return array The first element represents the status, the second contains additional information
193 protected function handleRouteRequirements($pathinfo, $name, Route $route)
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);
200 // check HTTP scheme requirement
201 $scheme = $this->context->getScheme();
202 $status = $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
204 return array($status, null);
208 * Get merged default parameters.
210 * @param array $params The parameters
211 * @param array $defaults The defaults
213 * @return array Merged default parameters
215 protected function mergeDefaults($params, $defaults)
217 foreach ($params as $key => $value) {
219 $defaults[$key] = $value;
226 protected function getExpressionLanguage()
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.');
232 $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
235 return $this->expressionLanguage;
241 protected function createRequest($pathinfo)
243 if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
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(),