OSDN Git Service

add find route by name
authorfrostbane <frostbane@programmer.net>
Tue, 25 Feb 2020 07:47:37 +0000 (16:47 +0900)
committerfrostbane <frostbane@programmer.net>
Tue, 25 Feb 2020 07:47:37 +0000 (16:47 +0900)
src/Router.php
tests/src/PHPRouterTest/RouterTest.php

index 70fd0d5..a29f506 100755 (executable)
@@ -128,6 +128,27 @@ class Router
         return $this->match($requestUrl, $requestMethod);
     }
 
+    public function findRouteByName($name)
+    {
+
+        if (empty($name)) {
+            return null;
+        }
+
+        $foundRoute = null;
+        $allRoutes  = $this->routes->all();
+
+        for ($i = count($allRoutes) - 1; $i >= 0; $i--) {
+            $route = $allRoutes[$i];
+
+            if ($route->getName() === $name) {
+                $foundRoute = $route;
+            }
+        }
+
+        return $foundRoute;
+    }
+
     private function findRoute($requestUrl, $requestMethod)
     {
         $currentDir = dirname($_SERVER['SCRIPT_NAME']);
index acd40e7..7cee361 100644 (file)
@@ -308,7 +308,7 @@ class RouterTest extends PHPUnit_Framework_TestCase
         $_SERVER["REQUEST_METHOD"] = "GET";
 
         $hasRoute = $router->requestHasValidRoute();
-        $route = $router->getRequestRoute();
+        $route    = $router->getRequestRoute();
 
         $this->assertTrue($hasRoute);
         $this->assertEquals("404", $route->getName());
@@ -317,6 +317,35 @@ class RouterTest extends PHPUnit_Framework_TestCase
         unset($_SERVER["REQUEST_METHOD"]);
     }
 
+    public function testFindRouteByName()
+    {
+        $collection = new RouteCollection();
+        $name       = "test_page";
+        $action     = '\PHPRouter\Test\Fixtures\CustomController::index';
+
+        $collection->attachRoute(new Route('/test', array(
+            '_controller' => $action,
+            'methods'     => 'GET',
+            'name'        => $name,
+        )));
+        $collection->attachRoute(new Route('/test', array(
+            '_controller' => '\PHPRouter\Test\Fixtures\CustomController::_404',
+            'methods'     => 'GET',
+            'name'        => '404',
+        )));
+
+        $router = new Router($collection);
+
+        $route = $router->findRouteByName($name);
+
+        $this->assertNotNull($route);
+        $this->assertEquals($action, $route->getClass() . "::" . $route->getAction());
+
+        $invalidRoute = $router->findRouteByName("non existing route");
+
+        $this->assertNull($invalidRoute);
+    }
+
     public function testParseConfig()
     {
         $config = Config::loadFromFile(__DIR__ . '/../../Fixtures/router.yaml');