Переглянути джерело

[Routing] Added optional trailing slash support to ApacheMatcherDumper

Jordi Boggiano 14 роки тому
батько
коміт
5bf593353f

+ 5 - 0
src/Symfony/Component/Routing/Matcher/Dumper/ApacheMatcherDumper.php

@@ -68,6 +68,11 @@ class ApacheMatcherDumper extends MatcherDumper
             $conditions = count($conditions) ? implode(" [OR]\n", $conditions)."\n" : '';
 
             $regexes[] = sprintf("%sRewriteCond %%{PATH_INFO} %s\nRewriteRule .* %s [QSA,L,%s]", $conditions, $regex, $options['script_name'], $variables);
+
+            // add redirect for missing trailing slash
+            if ('/$' === substr($regex, -2) && '^/$' !== $regex) {
+                $regexes[count($regexes)-1] .= sprintf("\nRewriteCond %%{PATH_INFO} %s\nRewriteRule .* /$0/ [QSA,L,R=301]", substr($regex, 0, -2).'$');
+            }
         }
 
         return implode("\n\n", $regexes);

+ 11 - 1
tests/Symfony/Tests/Component/Routing/Fixtures/dumper/url_matcher1.apache

@@ -3,4 +3,14 @@ RewriteRule .* app.php [QSA,L,E=_ROUTING__route:foo,E=_ROUTING_bar:%1,E=_ROUTING
 
 RewriteCond %{REQUEST_METHOD} ^(GET|head) [NC]
 RewriteCond %{PATH_INFO} ^/bar/([^/\.]+?)$
-RewriteRule .* app.php [QSA,L,E=_ROUTING__route:bar,E=_ROUTING_foo:%1]
+RewriteRule .* app.php [QSA,L,E=_ROUTING__route:bar,E=_ROUTING_foo:%1]
+
+RewriteCond %{PATH_INFO} ^/test/baz/$
+RewriteRule .* app.php [QSA,L,E=_ROUTING__route:baz]
+RewriteCond %{PATH_INFO} ^/test/baz$
+RewriteRule .* /$0/ [QSA,L,R=301]
+
+RewriteCond %{PATH_INFO} ^/test/([^/\.]+?)/$
+RewriteRule .* app.php [QSA,L,E=_ROUTING__route:baz2,E=_ROUTING_foo:%1]
+RewriteCond %{PATH_INFO} ^/test/([^/\.]+?)$
+RewriteRule .* /$0/ [QSA,L,R=301]

+ 7 - 1
tests/Symfony/Tests/Component/Routing/Matcher/Dumper/ApacheMatcherDumperTest.php

@@ -38,7 +38,13 @@ class ApacheMatcherDumperTest extends \PHPUnit_Framework_TestCase
             array(),
             array('_method' => 'GET|head')
         ));
-        
+        $collection->add('baz', new Route(
+            '/test/baz/'
+        ));
+        $collection->add('baz2', new Route(
+            '/test/{foo}/'
+        ));
+
         $dumper = new ApacheMatcherDumper($collection);
 
         $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher1.apache', $dumper->dump(), '->dump() dumps basic routes to the correct apache format.');