From: frostbane Date: Tue, 25 Feb 2020 07:47:37 +0000 (+0900) Subject: add find route by name X-Git-Tag: 2.0.4^2 X-Git-Url: http://git.osdn.net/view?p=php-libraries%2FRouter.git;a=commitdiff_plain;h=25a5d4b84de38125fb00720403fad1a962e69a30 add find route by name --- diff --git a/src/Router.php b/src/Router.php index 70fd0d5..a29f506 100755 --- a/src/Router.php +++ b/src/Router.php @@ -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']); diff --git a/tests/src/PHPRouterTest/RouterTest.php b/tests/src/PHPRouterTest/RouterTest.php index acd40e7..7cee361 100644 --- a/tests/src/PHPRouterTest/RouterTest.php +++ b/tests/src/PHPRouterTest/RouterTest.php @@ -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');