Skip to content

Commit

Permalink
Merge pull request #5 from crosa7/feature-get-route-by-name
Browse files Browse the repository at this point in the history
Feature: Get route by name
  • Loading branch information
mychidarko committed May 31, 2023
2 parents b0e065f + bec034c commit ce092ed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Router.php
Expand Up @@ -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];
}
}
15 changes: 15 additions & 0 deletions tests/routes.test.php
Expand Up @@ -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);
});

0 comments on commit ce092ed

Please sign in to comment.