OSDN Git Service

search route in reverse
authorfrostbane <frostbane@programmer.net>
Tue, 10 Dec 2019 01:58:44 +0000 (10:58 +0900)
committerfrostbane <frostbane@programmer.net>
Tue, 10 Dec 2019 02:00:12 +0000 (11:00 +0900)
src/RouteCollection.php
src/Router.php
tests/Fixtures/CustomController.php
tests/src/PHPRouterTest/RouterTest.php

index 221cbd1..5596914 100755 (executable)
@@ -42,6 +42,7 @@ class RouteCollection extends \SplObjectStorage
     public function all()
     {
         $temp = array();
+
         foreach ($this as $route) {
             $temp[] = $route;
         }
index a3919d4..1cf9934 100755 (executable)
@@ -118,7 +118,13 @@ class Router
             $currentDir = "";
         }
 
-        foreach ($this->routes->all() as $routes) {
+        $allRoutes = $this->routes->all();
+
+        // reverse search, last registered route will overwrite
+        // previously registered route
+        for ($i = count($allRoutes) - 1; $i >= 0; $i--) {
+            $routes = $allRoutes[$i];
+
             // compare server request method with route's allowed http methods
             if (!in_array($requestMethod, (array)$routes->getMethods(), true)) {
                 continue;
index 6d597e5..5553ad1 100644 (file)
@@ -23,4 +23,9 @@ final class CustomController
     {
         echo "home $this->config";
     }
+
+    public function _404()
+    {
+        return "cannot find page";
+    }
 }
index f6d2ca5..eb49547 100644 (file)
@@ -225,6 +225,36 @@ class RouterTest extends PHPUnit_Framework_TestCase
         );
     }
 
+    public function testRouteOverwrite()
+    {
+        $collection = new RouteCollection();
+
+        $collection->attachRoute(new Route('/test', array(
+            '_controller' => '\PHPRouter\Test\Fixtures\CustomController::index',
+            'methods'     => 'GET',
+            'name'        => 'test_page',
+        )));
+        $collection->attachRoute(new Route('/test', array(
+            '_controller' => '\PHPRouter\Test\Fixtures\CustomController::_404',
+            'methods'     => 'GET',
+            'name'        => '404',
+        )));
+
+        $router = new Router($collection);
+
+        $_SERVER["REQUEST_URI"]    = "/test";
+        $_SERVER["REQUEST_METHOD"] = "GET";
+
+        $hasRoute = $router->requestHasValidRoute();
+        $route = $router->getRequestRoute();
+
+        $this->assertTrue($hasRoute);
+        $this->assertEquals("404", $route->getName());
+
+        unset($_SERVER["REQUEST_URI"]);
+        unset($_SERVER["REQUEST_METHOD"]);
+    }
+
     public function testParseConfig()
     {
         $config = Config::loadFromFile(__DIR__ . '/../../Fixtures/router.yaml');