Skip to content

[Routing] fix trailing slash redirection when using RedirectableUrlMatcher #29298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 63 additions & 30 deletions src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class PhpMatcherDumper extends MatcherDumper
{
private $expressionLanguage;
private $signalingException;
private $supportsRedirections;

/**
* @var ExpressionFunctionProviderInterface[]
Expand Down Expand Up @@ -56,7 +57,7 @@ public function dump(array $options = array())

// trailing slash support is only enabled if we know how to redirect the user
$interfaces = class_implements($options['base_class']);
$supportsRedirections = isset($interfaces[RedirectableUrlMatcherInterface::class]);
$this->supportsRedirections = isset($interfaces[RedirectableUrlMatcherInterface::class]);

return <<<EOF
<?php
Expand All @@ -76,7 +77,7 @@ public function __construct(RequestContext \$context)
\$this->context = \$context;
}

{$this->generateMatchMethod($supportsRedirections)}
{$this->generateMatchMethod()}
}

EOF;
Expand All @@ -90,7 +91,7 @@ public function addExpressionLanguageProvider(ExpressionFunctionProviderInterfac
/**
* Generates the code for the match method implementing UrlMatcherInterface.
*/
private function generateMatchMethod(bool $supportsRedirections): string
private function generateMatchMethod(): string
{
// Group hosts by same-suffix, re-order when possible
$matchHost = false;
Expand All @@ -111,7 +112,7 @@ private function generateMatchMethod(bool $supportsRedirections): string
$code = <<<EOF
{
\$allow = \$allowSchemes = array();
\$pathinfo = rawurldecode(\$rawPathinfo);
\$pathinfo = rawurldecode(\$rawPathinfo) ?: '/';
\$context = \$this->context;
\$requestMethod = \$canonicalMethod = \$context->getMethod();
{$fetchHost}
Expand All @@ -123,7 +124,7 @@ private function generateMatchMethod(bool $supportsRedirections): string

EOF;

if ($supportsRedirections) {
if ($this->supportsRedirections) {
return <<<'EOF'
public function match($pathinfo)
{
Expand Down Expand Up @@ -213,9 +214,18 @@ private function groupStaticRoutes(RouteCollection $collection): array
$compiledRoute = $route->compile();
$hostRegex = $compiledRoute->getHostRegex();
$regex = $compiledRoute->getRegex();
if ($hasTrailingSlash = '/' !== $route->getPath()) {
$pos = strrpos($regex, '$');
$hasTrailingSlash = '/' === $regex[$pos - 1];
$regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
}

if (!$compiledRoute->getPathVariables()) {
$host = !$compiledRoute->getHostVariables() ? $route->getHost() : '';
$url = $route->getPath();
if ($hasTrailingSlash) {
$url = substr($url, 0, -1);
}
foreach ($dynamicRegex as list($hostRx, $rx)) {
if (preg_match($rx, $url) && (!$host || !$hostRx || preg_match($hostRx, $host))) {
$dynamicRegex[] = array($hostRegex, $regex);
Expand All @@ -224,7 +234,7 @@ private function groupStaticRoutes(RouteCollection $collection): array
}
}

$staticRoutes[$url][$name] = $route;
$staticRoutes[$url][$name] = array($route, $hasTrailingSlash);
} else {
$dynamicRegex[] = array($hostRegex, $regex);
$dynamicRoutes->add($name, $route);
Expand All @@ -251,7 +261,7 @@ private function compileStaticRoutes(array $staticRoutes, bool $matchHost): stri

foreach ($staticRoutes as $url => $routes) {
if (1 === \count($routes)) {
foreach ($routes as $name => $route) {
foreach ($routes as $name => list($route, $hasTrailingSlash)) {
}

if (!$route->getCondition()) {
Expand All @@ -261,20 +271,21 @@ private function compileStaticRoutes(array $staticRoutes, bool $matchHost): stri
unset($defaults['_canonical_route']);
}
$default .= sprintf(
"%s => array(%s, %s, %s, %s),\n",
"%s => array(%s, %s, %s, %s, %s),\n",
self::export($url),
self::export(array('_route' => $name) + $defaults),
self::export(!$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex() ?: null),
self::export(array_flip($route->getMethods()) ?: null),
self::export(array_flip($route->getSchemes()) ?: null)
self::export(array_flip($route->getSchemes()) ?: null),
self::export($hasTrailingSlash)
);
continue;
}
}

$code .= sprintf(" case %s:\n", self::export($url));
foreach ($routes as $name => $route) {
$code .= $this->compileRoute($route, $name, true);
foreach ($routes as $name => list($route, $hasTrailingSlash)) {
$code .= $this->compileRoute($route, $name, true, $hasTrailingSlash);
}
$code .= " break;\n";
}
Expand All @@ -285,15 +296,15 @@ private function compileStaticRoutes(array $staticRoutes, bool $matchHost): stri
\$routes = array(
{$this->indent($default, 4)} );

if (!isset(\$routes[\$pathinfo])) {
if (!isset(\$routes[\$trimmedPathinfo])) {
break;
}
list(\$ret, \$requiredHost, \$requiredMethods, \$requiredSchemes) = \$routes[\$pathinfo];
list(\$ret, \$requiredHost, \$requiredMethods, \$requiredSchemes, \$hasTrailingSlash) = \$routes[\$trimmedPathinfo];
{$this->compileSwitchDefault(false, $matchHost)}
EOF;
}

return sprintf(" switch (\$pathinfo) {\n%s }\n\n", $this->indent($code));
return sprintf(" switch (\$trimmedPathinfo = '/' !== \$pathinfo && '/' === \$pathinfo[-1] ? substr(\$pathinfo, 0, -1) : \$pathinfo) {\n%s }\n\n", $this->indent($code));
}

/**
Expand Down Expand Up @@ -394,7 +405,11 @@ private function compileDynamicRoutes(RouteCollection $collection, bool $matchHo

$state->vars = array();
$regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]);
$tree->addRoute($regex, array($name, $regex, $state->vars, $route));
if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {
$regex = substr($regex, 0, -1);
}

$tree->addRoute($regex, array($name, $regex, $state->vars, $route, $hasTrailingSlash));
}

$code .= $this->compileStaticPrefixCollection($tree, $state);
Expand All @@ -403,7 +418,7 @@ private function compileDynamicRoutes(RouteCollection $collection, bool $matchHo
$code .= "\n .')'";
$state->regex .= ')';
}
$rx = ")$}{$modifiers}";
$rx = ")(?:/?)$}{$modifiers}";
$code .= "\n .'{$rx}',";
$state->regex .= $rx;
$state->markTail = 0;
Expand All @@ -423,7 +438,7 @@ private function compileDynamicRoutes(RouteCollection $collection, bool $matchHo
\$routes = array(
{$this->indent($state->default, 4)} );

list(\$ret, \$vars, \$requiredMethods, \$requiredSchemes) = \$routes[\$m];
list(\$ret, \$vars, \$requiredMethods, \$requiredSchemes, \$hasTrailingSlash) = \$routes[\$m];
{$this->compileSwitchDefault(true, $matchHost)}
EOF;
}
Expand Down Expand Up @@ -478,11 +493,11 @@ private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \st
continue;
}

list($name, $regex, $vars, $route) = $route;
list($name, $regex, $vars, $route, $hasTrailingSlash) = $route;
$compiledRoute = $route->compile();

if ($compiledRoute->getRegex() === $prevRegex) {
$state->switch = substr_replace($state->switch, $this->compileRoute($route, $name, false)."\n", -19, 0);
$state->switch = substr_replace($state->switch, $this->compileRoute($route, $name, false, $hasTrailingSlash)."\n", -19, 0);
continue;
}

Expand All @@ -501,12 +516,13 @@ private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \st
unset($defaults['_canonical_route']);
}
$state->default .= sprintf(
"%s => array(%s, %s, %s, %s),\n",
"%s => array(%s, %s, %s, %s, %s),\n",
$state->mark,
self::export(array('_route' => $name) + $defaults),
self::export($vars),
self::export(array_flip($route->getMethods()) ?: null),
self::export(array_flip($route->getSchemes()) ?: null)
self::export(array_flip($route->getSchemes()) ?: null),
self::export($hasTrailingSlash)
);
} else {
$prevRegex = $compiledRoute->getRegex();
Expand All @@ -518,7 +534,7 @@ private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \st

$state->switch .= <<<EOF
case {$state->mark}:
{$combine}{$this->compileRoute($route, $name, false)}
{$combine}{$this->compileRoute($route, $name, false, $hasTrailingSlash)}
break;

EOF;
Expand All @@ -533,8 +549,15 @@ private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \st
*/
private function compileSwitchDefault(bool $hasVars, bool $matchHost): string
{
$code = sprintf("
if ('/' !== \$pathinfo && \$hasTrailingSlash !== ('/' === \$pathinfo[-1])) {
%s;
}\n",
$this->supportsRedirections ? 'return null' : 'break'
);

if ($hasVars) {
$code = <<<EOF
$code .= <<<EOF

foreach (\$vars as \$i => \$v) {
if (isset(\$matches[1 + \$i])) {
Expand All @@ -544,7 +567,7 @@ private function compileSwitchDefault(bool $hasVars, bool $matchHost): string

EOF;
} elseif ($matchHost) {
$code = <<<EOF
$code .= <<<EOF

if (\$requiredHost) {
if ('#' !== \$requiredHost[0] ? \$requiredHost !== \$host : !preg_match(\$requiredHost, \$host, \$hostMatches)) {
Expand All @@ -557,8 +580,6 @@ private function compileSwitchDefault(bool $hasVars, bool $matchHost): string
}

EOF;
} else {
$code = '';
}

$code .= <<<EOF
Expand Down Expand Up @@ -587,9 +608,22 @@ private function compileSwitchDefault(bool $hasVars, bool $matchHost): string
*
* @throws \LogicException
*/
private function compileRoute(Route $route, string $name, bool $checkHost): string
private function compileRoute(Route $route, string $name, bool $checkHost, bool $hasTrailingSlash): string
{
$code = '';
$code = " // $name";

if ('/' !== $route->getPath()) {
$code .= sprintf("
if ('/' !== \$pathinfo && '/' %s \$pathinfo[-1]) {
%s;
}\n",
$hasTrailingSlash ? '!==' : '===',
$this->supportsRedirections ? 'return null' : 'break'
);
} else {
$code .= "\n";
}

$compiledRoute = $route->compile();
$conditions = array();
$matches = (bool) $compiledRoute->getPathVariables();
Expand Down Expand Up @@ -617,12 +651,11 @@ private function compileRoute(Route $route, string $name, bool $checkHost): stri

if ($conditions) {
$code .= <<<EOF
// $name
if ($conditions) {

EOF;
} else {
$code .= " // {$name}\n";
$code = $this->indent($code);
}

$gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
Expand Down
26 changes: 24 additions & 2 deletions src/Symfony/Component/Routing/Matcher/UrlMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,18 +130,40 @@ public function addExpressionLanguageProvider(ExpressionFunctionProviderInterfac
*/
protected function matchCollection($pathinfo, RouteCollection $routes)
{
$supportsTrailingSlash = '/' !== $pathinfo && '' !== $pathinfo && $this instanceof RedirectableUrlMatcherInterface;

foreach ($routes as $name => $route) {
$compiledRoute = $route->compile();
$staticPrefix = $compiledRoute->getStaticPrefix();

// check the static prefix of the URL first. Only use the more expensive preg_match when it matches
if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
if ('' === $staticPrefix || 0 === strpos($pathinfo, $staticPrefix)) {
// no-op
} elseif (!$supportsTrailingSlash) {
continue;
} elseif ('/' === $staticPrefix[-1] && substr($staticPrefix, 0, -1) === $pathinfo) {
return;
} elseif ('/' === $pathinfo[-1] && substr($pathinfo, 0, -1) === $staticPrefix) {
return;
} else {
continue;
}
$regex = $compiledRoute->getRegex();

if ($supportsTrailingSlash) {
$pos = strrpos($regex, '$');
$hasTrailingSlash = '/' === $regex[$pos - 1];
$regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
}

if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
if (!preg_match($regex, $pathinfo, $matches)) {
continue;
}

if ($supportsTrailingSlash && $hasTrailingSlash !== ('/' === $pathinfo[-1])) {
return;
}

$hostMatches = array();
if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function __construct(RequestContext $context)
public function match($rawPathinfo)
{
$allow = $allowSchemes = array();
$pathinfo = rawurldecode($rawPathinfo);
$pathinfo = rawurldecode($rawPathinfo) ?: '/';
$context = $this->context;
$requestMethod = $canonicalMethod = $context->getMethod();

Expand Down
Loading