8000 [Routing][2.0] fixed several bugs and applied improvements by Tobion · Pull Request #3810 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Routing][2.0] fixed several bugs and applied improvements #3810

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

Closed
wants to merge 4 commits into from
Closed
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
233 changes: 90 additions & 143 deletions src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class PhpMatcherDumper extends MatcherDumper
{
Expand All @@ -44,97 +45,78 @@ public function dump(array $options = array())
$interfaces = class_implements($options['base_class']);
$supportsRedirections = isset($interfaces['Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface']);

return
$this->startClass($options['class'], $options['base_class']).
$this->addConstructor().
$this->addMatcher($supportsRedirections).
$this->endClass()
;
return <<<EOF
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
* {$options['class']}
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class {$options['class']} extends {$options['base_class']}
{
/**
* Constructor.
*/
public function __construct(RequestContext \$context)
{
\$this->context = \$context;
}

private function addMatcher($supportsRedirections)
{$this->generateMatchMethod($supportsRedirections)}
}

EOF;
}

private function generateMatchMethod($supportsRedirections)
{
// we need to deep clone the routes as we will modify the structure to optimize the dump
$code = implode("\n", $this->compileRoutes(clone $this->getRoutes(), $supportsRedirections));
$code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");

return <<<EOF

public function match(\$pathinfo)
{
\$allow = array();
\$pathinfo = urldecode(\$pathinfo);

$code

throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
}

EOF;
}

private function compileRoutes(RouteCollection $routes, $supportsRedirections, $parentPrefix = null)
{
$code = array();

$routeIterator = $routes->getIterator();
$keys = array_keys($routeIterator->getArrayCopy());
$keysCount = count($keys);

$i = 0;
foreach ($routeIterator as $name => $route) {
$i++;
$code = '';

foreach ($routes as $name => $route) {
if ($route instanceof RouteCollection) {
$prefix = $route->getPrefix();
$optimizable = $prefix && count($route->all()) > 1 && false === strpos($route->getPrefix(), '{');
$indent = '';
if ($optimizable) {
for ($j = $i; $j < $keysCount; $j++) {
if ($keys[$j] === null) {
continue;
}

$testRoute = $routeIterator->offsetGet($keys[$j]);
$isCollection = ($testRoute instanceof RouteCollection);

$testPrefix = $isCollection ? $testRoute->getPrefix() : $testRoute->getPattern();

if (0 === st 8000 rpos($testPrefix, $prefix)) {
$routeIterator->offsetUnset($keys[$j]);

if ($isCollection) {
$route->addCollection($testRoute);
} else {
$route->add($keys[$j], $testRoute);
}

$i++;
$keys[$j] = null;
$countWorth = count($route->all()) > 1;
// whether it's optimizable
if ('' !== $prefix && $prefix !== $parentPrefix && $countWorth && false === strpos($prefix, '{')) {
$code .= sprintf(" if (0 === strpos(\$pathinfo, %s)) {\n", var_export($prefix, true));

foreach (explode("\n", $this->compileRoutes($route, $supportsRedirections, $prefix)) as $line) {
if ('' !== $line) {
$code .= ' '; // apply extra indention
}
$code .= $line."\n";
}

if ($prefix !== $parentPrefix) {
$code[] = sprintf(" if (0 === strpos(\$pathinfo, %s)) {", var_export($prefix, true));
$indent = ' ';
}
}

foreach ($this->compileRoutes($route, $supportsRedirections, $prefix) as $line) {
foreach (explode("\n", $line) as $l) {
if ($l) {
$code[] = $indent.$l;
} else {
$code[] = $l;
}
}
}

if ($optimizable && $prefix !== $parentPrefix) {
$code[] = " }\n";
$code = substr($code, 0, -2); // remove redundant last two line breaks
$code .= " }\n\n";
} else {
$code .= $this->compileRoutes($route, $supportsRedirections, $countWorth ? $prefix : null);
}
} else {
foreach ($this->compileRoute($route, $name, $supportsRedirections, $parentPrefix) as $line) {
$code[] = $line;
}
$code .= $this->compileRoute($route, $name, $supportsRedirections, $parentPrefix)."\n";
}
}

Expand All @@ -143,25 +125,37 @@ private function compileRoutes(RouteCollection $routes, $supportsRedirections, $

private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
{
$code = array();
$code = '';
$compiledRoute = $route->compile();
$conditions = array();
$hasTrailingSlash = false;
$matches = false;
$methods = array();

if ($req = $route->getRequirement('_method')) {
$methods = explode('|', strtoupper($req));
// GET and HEAD are equivalent
if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
$methods[] = 'HEAD';
}
}

$supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));

if (!count($compiledRoute->getVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#', str_replace(array("\n", ' '), '', $compiledRoute->getRegex()), $m)) {
if ($supportsRedirections && substr($m['url'], -1) === '/') {
if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
$conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
$hasTrailingSlash = true;
} else {
$conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
}
} else {
if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() != $parentPrefix) {
if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
$conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
}

$regex = str_replace(array("\n", ' '), '', $compiledRoute->getRegex());
if ($supportsRedirections && $pos = strpos($regex, '/$')) {
if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
$regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
$hasTrailingSlash = true;
}
Expand All @@ -172,122 +166,75 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren

$conditions = implode(' && ', $conditions);

$gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);

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

EOF;

if ($req = $route->getRequirement('_method')) {
$methods = explode('|', strtoupper($req));
// GET and HEAD are equivalent
if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
$methods[] = 'HEAD';
}
if ($methods) {
$gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);

if (1 === count($methods)) {
$code[] = <<<EOF
$code .= <<<EOF
if (\$this->context->getMethod() != '$methods[0]') {
\$allow[] = '$methods[0]';
goto $gotoname;
}

EOF;
} else {
$methods = implode('\', \'', $methods);
$code[] = <<<EOF
$methods = implode("', '", $methods);
$code .= <<<EOF
if (!in_array(\$this->context->getMethod(), array('$methods'))) {
\$allow = array_merge(\$allow, array('$methods'));
goto $gotoname;
}

EOF;
}
}

if ($hasTrailingSlash) {
$code[] = sprintf(<<<EOF
$code .= <<<EOF
if (substr(\$pathinfo, -1) !== '/') {
return \$this->redirect(\$pathinfo.'/', '%s');
return \$this->redirect(\$pathinfo.'/', '$name');
}
EOF
, $name);

EOF;
}

if ($scheme = $route->getRequirement('_scheme')) {
if (!$supportsRedirections) {
throw new \LogicException('The "_scheme" requirement is only supported for route dumper that implements RedirectableUrlMatcherInterface.');
throw new \LogicException('The "_scheme" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
}

$code[] = sprintf(<<<EOF
$code .= <<<EOF
if (\$this->context->getScheme() !== '$scheme') {
return \$this->redirect(\$pathinfo, '%s', '$scheme');
return \$this->redirect(\$pathinfo, '$name', '$scheme');
}
EOF
, $name);

EOF;
}

// optimize parameters array
if (true === $matches && $compiledRoute->getDefaults()) {
$code[] = sprintf(" return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));"
$code .= sprintf(" return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));\n"
, str_replace("\n", '', var_export($compiledRoute->getDefaults(), true)), $name);
} elseif (true === $matches) {
$code[] = sprintf(" \$matches['_route'] = '%s';", $name);
$code[] = sprintf(" return \$matches;", $name);
$code .= sprintf(" \$matches['_route'] = '%s';\n", $name);
$code .= " return \$matches;\n";
} elseif ($compiledRoute->getDefaults()) {
$code[] = sprintf(' return %s;', str_replace("\n", '', var_export(array_merge($compiledRoute->getDefaults(), array('_route' => $name)), true)));
$code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_merge($compiledRoute->getDefaults(), array('_route' => $name)), true)));
} else {
$code[] = sprintf(" return array('_route' => '%s');", $name);
$code .= sprintf(" return array('_route' => '%s');\n", $name);
}
$code[] = " }";
$code .= " }\n";

if ($req) {
$code[] = " $gotoname:";
if ($methods) {
$code .= " $gotoname:\n";
}

$code[] = '';

return $code;
}

private function startClass($class, $baseClass)
{
return <<<EOF
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
* $class
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class $class extends $baseClass
{

EOF;
}

private function addConstructor()
{
return <<<EOF
/**
* Constructor.
*/
public function __construct(RequestContext \$context)
{
\$this->context = \$context;
}

EOF;
}

private function endClass()
{
return <<<EOF
}

EOF;
}
}
12 changes: 8 additions & 4 deletions src/Symfony/Component/Routing/Route.php
8BC2
Original file line number Diff line number Diff line change
Expand Up @@ -295,15 +295,19 @@ public function compile()

private function sanitizeRequirement($key, $regex)
{
if (is_array($regex)) {
throw new \InvalidArgumentException(sprintf('Routing requirements must be a string, array given for "%s"', $key));
if (!is_string($regex)) {
throw new \InvalidArgumentException(sprintf('Routing requirement for "%s" must be a string', $key));
}

if ('^' == $regex[0]) {
if ('' === $regex) {
throw new \InvalidArgumentException(sprintf('Routing requirement for "%s" cannot be empty', $key));
}

if ('^' === $regex[0]) {
$regex = substr($regex, 1);
}

if ('$' == substr($regex, -1)) {
if ('$' === substr($regex, -1)) {
$regex = substr($regex, 0, -1);
}

Expand Down
Loading
0