From bec034c0827ad266a2bc603e0e7f177ce1a9da19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Rosa?= Date: Sat, 20 May 2023 10:37:09 +0100 Subject: [PATCH] Feature: Get route by name - This introduces a method to return a route url by its name - The main usage idea behind this is, when we want to render some href in a template we would always have to pass the full route url. With this, we can simply define a route with a name and then in the templates we only need to call app()->route('route-name') and that is it, we get the url --- src/Router.php | 16 ++++++++++++++++ tests/routes.test.php | 15 +++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/Router.php b/src/Router.php index 83c50f8..b05895e 100644 --- a/src/Router.php +++ b/src/Router.php @@ -324,4 +324,20 @@ public static function push($route, ?array $data = null) return header("location: $route$data"); } + + /** + * Get route url by defined route name + * + * @param string $routeName + * + * @return string + */ + public static function route(string $routeName): string + { + if (!isset(static::$namedRoutes[$routeName])) { + trigger_error('Route named ' . $routeName . ' not found'); + } + + return static::$namedRoutes[$routeName]; + } } diff --git a/tests/routes.test.php b/tests/routes.test.php index ddb9d8f..3959247 100644 --- a/tests/routes.test.php +++ b/tests/routes.test.php @@ -108,3 +108,18 @@ class TRoute expect(TRoute::$val)->toBe(false); }); + +test('route should return url by route name', function () { + $router = new Router; + $router->match('GET', '/route/url', ['handler', 'name' => 'route-name']); + + $routeUrl = $router->route('route-name'); + + expect($routeUrl)->toBe('/route/url'); +}); + +test('route should throw exception if no route found for name', function () { + $router = new Router; + + expect(fn() => $router->route('non-existent-route-name'))->toThrow(Exception::class); +});