summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSam Light <sam@lightscale.co.uk>2026-06-10 19:00:32 +0100
committerSam Light <sam@lightscale.co.uk>2026-06-10 19:00:32 +0100
commit25d0c98dd7b69695d0b2a8aa24d991359b371455 (patch)
treed272b81f296f057d0d948f2e37022ebe712b0ba2
parent7f3ad6625e00e39cad47cbfca97e6b872712d10a (diff)
added named routes to router
-rw-r--r--src/Router.php13
-rw-r--r--tests/Unit/RouterTest.php26
2 files changed, 36 insertions, 3 deletions
diff --git a/src/Router.php b/src/Router.php
index 5757b35..9aa3b55 100644
--- a/src/Router.php
+++ b/src/Router.php
@@ -15,6 +15,9 @@ class Router
private PathSegment $root;
private Strategy $strategy;
+ /** @var array<string, Route> */
+ private array $namedRoutes = [];
+
public function __construct()
{
$this->root = new PathSegment(type: PathSegmentType::Root);
@@ -161,4 +164,14 @@ class Router
{
return $this->route(HttpMethod::Any, $path, $handler);
}
+
+ public function addNamedRoute(string $name, Route $route): void
+ {
+ $this->namedRoutes[$name] = $route;
+ }
+
+ public function getNamedRoute(string $name): ?Route
+ {
+ return $this->namedRoutes[$name] ?? null;
+ }
}
diff --git a/tests/Unit/RouterTest.php b/tests/Unit/RouterTest.php
index 31e391d..41b794d 100644
--- a/tests/Unit/RouterTest.php
+++ b/tests/Unit/RouterTest.php
@@ -227,12 +227,32 @@ it('makes a :dataset route')
->toBeInstanceOf(RouteMatch::class);
it('returns RouteDefinition when making route')
- ->expect(fn() => (new Router())
- ->route(HttpMethod::Get, '/test', fn() => null)
+ ->expect(fn () => (new Router())
+ ->route(HttpMethod::Get, '/test', fn () => null)
)
->toBeInstanceOf(RouteDefinition::class);
it('returns RouteDefinition when making :dataset route')
->with($methodGenerator)
- ->expect(fn (HttpMethod $m) => (new Router)->{$m->value}('/test', fn() => null))
+ ->expect(fn (HttpMethod $m) => (new Router())->{$m->value}('/test', fn () => null))
->toBeInstanceOf(RouteDefinition::class);
+
+it('has named routes', function () {
+ $router = new Router();
+ $route = new Route(HttpMethod::Get, fn () => null);
+ $router->addNamedRoute('hello-hello', $route);
+
+ expect($router->getNamedRoute('hello-hello'))->toBe($route);
+});
+
+it('overrides existing named routes', function () {
+ $router = new Router();
+ $route1 = new Route(HttpMethod::Get, fn () => null);
+ $route2 = new Route(HttpMethod::Post, fn () => null);
+ $router->addNamedRoute('hello-hello', $route1);
+ $router->addNamedRoute('hello-hello', $route2);
+
+ expect($router->getNamedRoute('hello-hello'))
+ ->not->toBe($route1)
+ ->toBe($route2);
+});