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\Dumper;
14 use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
15 use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
16 use Symfony\Component\Routing\Route;
17 use Symfony\Component\Routing\RouteCollection;
20 * PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
22 * @author Fabien Potencier <fabien@symfony.com>
23 * @author Tobias Schultze <http://tobion.de>
24 * @author Arnaud Le Blanc <arnaud.lb@gmail.com>
26 class PhpMatcherDumper extends MatcherDumper
28 private $expressionLanguage;
31 * @var ExpressionFunctionProviderInterface[]
33 private $expressionLanguageProviders = array();
36 * Dumps a set of routes to a PHP class.
40 * * class: The class name
41 * * base_class: The base class name
43 * @param array $options An array of options
45 * @return string A PHP class representing the matcher class
47 public function dump(array $options = array())
49 $options = array_replace(array(
50 'class' => 'ProjectUrlMatcher',
51 'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
54 // trailing slash support is only enabled if we know how to redirect the user
55 $interfaces = class_implements($options['base_class']);
56 $supportsRedirections = isset($interfaces['Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcherInterface']);
61 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
62 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
63 use Symfony\Component\Routing\RequestContext;
66 * This class has been auto-generated
67 * by the Symfony Routing Component.
69 class {$options['class']} extends {$options['base_class']}
71 public function __construct(RequestContext \$context)
73 \$this->context = \$context;
76 {$this->generateMatchMethod($supportsRedirections)}
82 public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
84 $this->expressionLanguageProviders[] = $provider;
88 * Generates the code for the match method implementing UrlMatcherInterface.
90 * @param bool $supportsRedirections Whether redirections are supported by the base class
92 * @return string Match method as PHP code
94 private function generateMatchMethod($supportsRedirections)
96 $code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
99 public function match(\$rawPathinfo)
102 \$pathinfo = rawurldecode(\$rawPathinfo);
103 \$trimmedPathinfo = rtrim(\$pathinfo, '/');
104 \$context = \$this->context;
105 \$request = \$this->request ?: \$this->createRequest(\$pathinfo);
106 \$requestMethod = \$canonicalMethod = \$context->getMethod();
108 if ('HEAD' === \$requestMethod) {
109 \$canonicalMethod = 'GET';
114 throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
120 * Generates PHP code to match a RouteCollection with all its routes.
122 * @param RouteCollection $routes A RouteCollection instance
123 * @param bool $supportsRedirections Whether redirections are supported by the base class
125 * @return string PHP code
127 private function compileRoutes(RouteCollection $routes, $supportsRedirections)
129 $fetchedHost = false;
130 $groups = $this->groupRoutesByHostRegex($routes);
133 foreach ($groups as $collection) {
134 if (null !== $regex = $collection->getAttribute('host_regex')) {
136 $code .= " \$host = \$context->getHost();\n\n";
140 $code .= sprintf(" if (preg_match(%s, \$host, \$hostMatches)) {\n", var_export($regex, true));
143 $tree = $this->buildStaticPrefixCollection($collection);
144 $groupCode = $this->compileStaticPrefixRoutes($tree, $supportsRedirections);
146 if (null !== $regex) {
147 // apply extra indention at each line (except empty ones)
148 $groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
156 // used to display the Welcome Page in apps that don't define a homepage
157 $code .= " if ('/' === \$pathinfo && !\$allow) {\n";
158 $code .= " throw new Symfony\Component\Routing\Exception\NoConfigurationException();\n";
164 private function buildStaticPrefixCollection(DumperCollection $collection)
166 $prefixCollection = new StaticPrefixCollection();
168 foreach ($collection as $dumperRoute) {
169 $prefix = $dumperRoute->getRoute()->compile()->getStaticPrefix();
170 $prefixCollection->addRoute($prefix, $dumperRoute);
173 $prefixCollection->optimizeGroups();
175 return $prefixCollection;
179 * Generates PHP code to match a tree of routes.
181 * @param StaticPrefixCollection $collection A StaticPrefixCollection instance
182 * @param bool $supportsRedirections Whether redirections are supported by the base class
183 * @param string $ifOrElseIf either "if" or "elseif" to influence chaining
185 * @return string PHP code
187 private function compileStaticPrefixRoutes(StaticPrefixCollection $collection, $supportsRedirections, $ifOrElseIf = 'if')
190 $prefix = $collection->getPrefix();
192 if (!empty($prefix) && '/' !== $prefix) {
193 $code .= sprintf(" %s (0 === strpos(\$pathinfo, %s)) {\n", $ifOrElseIf, var_export($prefix, true));
198 foreach ($collection->getItems() as $route) {
199 if ($route instanceof StaticPrefixCollection) {
200 $code .= $this->compileStaticPrefixRoutes($route, $supportsRedirections, $ifOrElseIf);
201 $ifOrElseIf = 'elseif';
203 $code .= $this->compileRoute($route[1]->getRoute(), $route[1]->getName(), $supportsRedirections, $prefix)."\n";
208 if (!empty($prefix) && '/' !== $prefix) {
210 // apply extra indention at each line (except empty ones)
211 $code = preg_replace('/^.{2,}$/m', ' $0', $code);
218 * Compiles a single Route to PHP code used to match it against the path info.
220 * @param Route $route A Route instance
221 * @param string $name The name of the Route
222 * @param bool $supportsRedirections Whether redirections are supported by the base class
223 * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
225 * @return string PHP code
227 * @throws \LogicException
229 private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
232 $compiledRoute = $route->compile();
233 $conditions = array();
234 $hasTrailingSlash = false;
236 $hostMatches = false;
237 $methods = $route->getMethods();
239 $supportsTrailingSlash = $supportsRedirections && (!$methods || \in_array('GET', $methods));
240 $regex = $compiledRoute->getRegex();
242 if (!\count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#'.('u' === substr($regex, -1) ? 'u' : ''), $regex, $m)) {
243 if ($supportsTrailingSlash && '/' === substr($m['url'], -1)) {
244 $conditions[] = sprintf('%s === $trimmedPathinfo', var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
245 $hasTrailingSlash = true;
247 $conditions[] = sprintf('%s === $pathinfo', var_export(str_replace('\\', '', $m['url']), true));
250 if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
251 $conditions[] = sprintf('0 === strpos($pathinfo, %s)', var_export($compiledRoute->getStaticPrefix(), true));
254 if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
255 $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
256 $hasTrailingSlash = true;
258 $conditions[] = sprintf('preg_match(%s, $pathinfo, $matches)', var_export($regex, true));
263 if ($compiledRoute->getHostVariables()) {
267 if ($route->getCondition()) {
268 $conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), array('context', 'request'));
271 $conditions = implode(' && ', $conditions);
279 $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
281 // the offset where the return value is appended below, with indendation
282 $retOffset = 12 + \strlen($code);
284 // optimize parameters array
285 if ($matches || $hostMatches) {
288 $vars[] = '$hostMatches';
291 $vars[] = '$matches';
293 $vars[] = "array('_route' => '$name')";
296 " \$ret = \$this->mergeDefaults(array_replace(%s), %s);\n",
297 implode(', ', $vars),
298 str_replace("\n", '', var_export($route->getDefaults(), true))
300 } elseif ($route->getDefaults()) {
301 $code .= sprintf(" \$ret = %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
303 $code .= sprintf(" \$ret = array('_route' => '%s');\n", $name);
306 if ($hasTrailingSlash) {
308 if ('/' === substr(\$pathinfo, -1)) {
310 } elseif ('GET' !== \$canonicalMethod) {
313 return array_replace(\$ret, \$this->redirect(\$rawPathinfo.'/', '$name'));
321 $methodVariable = \in_array('GET', $methods) ? '$canonicalMethod' : '$requestMethod';
322 $methods = implode("', '", $methods);
325 if ($schemes = $route->getSchemes()) {
326 if (!$supportsRedirections) {
327 throw new \LogicException('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
329 $schemes = str_replace("\n", '', var_export(array_flip($schemes), true));
332 \$requiredSchemes = $schemes;
333 \$hasRequiredScheme = isset(\$requiredSchemes[\$context->getScheme()]);
334 if (!in_array($methodVariable, array('$methods'))) {
335 if (\$hasRequiredScheme) {
336 \$allow = array_merge(\$allow, array('$methods'));
340 if (!\$hasRequiredScheme) {
341 if ('GET' !== \$canonicalMethod) {
345 return array_replace(\$ret, \$this->redirect(\$rawPathinfo, '$name', key(\$requiredSchemes)));
352 \$requiredSchemes = $schemes;
353 if (!isset(\$requiredSchemes[\$context->getScheme()])) {
354 if ('GET' !== \$canonicalMethod) {
358 return array_replace(\$ret, \$this->redirect(\$rawPathinfo, '$name', key(\$requiredSchemes)));
364 } elseif ($methods) {
366 if (!in_array($methodVariable, array('$methods'))) {
367 \$allow = array_merge(\$allow, array('$methods'));
375 if ($hasTrailingSlash || $schemes || $methods) {
376 $code .= " return \$ret;\n";
378 $code = substr_replace($code, 'return', $retOffset, 6);
382 if ($hasTrailingSlash || $schemes || $methods) {
383 $code .= " $gotoname:\n";
390 * Groups consecutive routes having the same host regex.
392 * The result is a collection of collections of routes having the same host regex.
394 * @param RouteCollection $routes A flat RouteCollection
396 * @return DumperCollection A collection with routes grouped by host regex in sub-collections
398 private function groupRoutesByHostRegex(RouteCollection $routes)
400 $groups = new DumperCollection();
401 $currentGroup = new DumperCollection();
402 $currentGroup->setAttribute('host_regex', null);
403 $groups->add($currentGroup);
405 foreach ($routes as $name => $route) {
406 $hostRegex = $route->compile()->getHostRegex();
407 if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
408 $currentGroup = new DumperCollection();
409 $currentGroup->setAttribute('host_regex', $hostRegex);
410 $groups->add($currentGroup);
412 $currentGroup->add(new DumperRoute($name, $route));
418 private function getExpressionLanguage()
420 if (null === $this->expressionLanguage) {
421 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
422 throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
424 $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
427 return $this->expressionLanguage;