Pārlūkot izejas kodu

[HttpFoundation] allow locale in RequestMatcher path

Johannes M. Schmitt 14 gadi atpakaļ
vecāks
revīzija
88becfe3f8

+ 15 - 7
src/Symfony/Component/HttpFoundation/RequestMatcher.php

@@ -18,11 +18,11 @@ namespace Symfony\Component\HttpFoundation;
  */
 class RequestMatcher implements RequestMatcherInterface
 {
-    protected $path;
-    protected $host;
-    protected $methods;
-    protected $ip;
-    protected $attributes;
+    private $path;
+    private $host;
+    private $methods;
+    private $ip;
+    private $attributes;
 
     public function __construct($path = null, $host = null, $methods = null, $ip = null, array $attributes = array())
     {
@@ -105,8 +105,16 @@ class RequestMatcher implements RequestMatcherInterface
             }
         }
 
-        if (null !== $this->path && !preg_match('#'.str_replace('#', '\\#', $this->path).'#', $request->getPathInfo())) {
-            return false;
+        if (null !== $this->path) {
+            if (null !== $session = $request->getSession()) {
+                $path = strtr($this->path, array('{_locale}' => $session->getLocale(), '#' => '\\#'));
+            } else {
+                $path = str_replace('#', '\\#', $this->path);
+            }
+
+            if (!preg_match('#'.$path.'#', $request->getPathInfo())) {
+                return false;
+            }
         }
 
         if (null !== $this->host && !preg_match('#'.str_replace('#', '\\#', $this->host).'#', $request->getHost())) {

+ 20 - 0
tests/Symfony/Tests/Component/HttpFoundation/RequestMatcherTest.php

@@ -11,6 +11,10 @@
 
 namespace Symfony\Tests\Component\HttpFoundation;
 
+use Symfony\Component\HttpFoundation\SessionStorage\ArraySessionStorage;
+
+use Symfony\Component\HttpFoundation\Session;
+
 use Symfony\Component\HttpFoundation\RequestMatcher;
 use Symfony\Component\HttpFoundation\Request;
 
@@ -93,6 +97,22 @@ class RequestMatcherTest extends \PHPUnit_Framework_TestCase
         $this->assertFalse($matcher->matches($request));
     }
 
+    public function testPathWithLocale()
+    {
+        $matcher = new RequestMatcher();
+        $request = Request::create('/en/login');
+
+        $session = new Session(new ArraySessionStorage());
+        $session->setLocale('en');
+        $request->setSession($session);
+
+        $matcher->matchPath('^/{_locale}/login$');
+        $this->assertTrue($matcher->matches($request));
+
+        $session->setLocale('de');
+        $this->assertFalse($matcher->matches($request));
+    }
+
     public function testAttributes()
     {
         $matcher = new RequestMatcher();