Skip to content

Commit 72e88c8

Browse files
authored
feat: allow hard-coded uris in router::touri (tempestphp#490)
1 parent c57b1ac commit 72e88c8

File tree

2 files changed

+21
-14
lines changed

2 files changed

+21
-14
lines changed

src/Tempest/Http/src/GenericRouter.php

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Closure;
88
use Psr\Http\Message\ServerRequestInterface as PsrRequest;
9+
use ReflectionException;
910
use Tempest\Container\Container;
1011
use Tempest\Core\AppConfig;
1112
use Tempest\Http\Exceptions\ControllerActionHasNoReturn;
@@ -120,23 +121,27 @@ private function getCallable(MatchedRoute $matchedRoute): Closure
120121

121122
public function toUri(array|string $action, ...$params): string
122123
{
123-
if (is_array($action)) {
124-
$controllerClass = $action[0];
125-
$reflection = new ClassReflector($controllerClass);
126-
$controllerMethod = $reflection->getMethod($action[1]);
127-
} else {
128-
$controllerClass = $action;
129-
$reflection = new ClassReflector($controllerClass);
130-
$controllerMethod = $reflection->getMethod('__invoke');
131-
}
124+
try {
125+
if (is_array($action)) {
126+
$controllerClass = $action[0];
127+
$reflection = new ClassReflector($controllerClass);
128+
$controllerMethod = $reflection->getMethod($action[1]);
129+
} else {
130+
$controllerClass = $action;
131+
$reflection = new ClassReflector($controllerClass);
132+
$controllerMethod = $reflection->getMethod('__invoke');
133+
}
132134

133-
$routeAttribute = $controllerMethod->getAttribute(Route::class);
135+
$routeAttribute = $controllerMethod->getAttribute(Route::class);
134136

135-
if ($routeAttribute === null) {
136-
throw new InvalidRouteException($controllerClass, $controllerMethod->getName());
137-
}
137+
$uri = $routeAttribute->uri;
138+
} catch (ReflectionException) {
139+
if (is_array($action)) {
140+
throw new InvalidRouteException($action[0], $action[1]);
141+
}
138142

139-
$uri = $routeAttribute->uri;
143+
$uri = $action;
144+
}
140145

141146
$queryParams = [];
142147

tests/Integration/Route/RouterTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ public function test_generate_uri(): void
5656
$this->container->config($appConfig);
5757
$router = $this->container->get(GenericRouter::class);
5858
$this->assertEquals('https://test.com/test/1/a', $router->toUri([TestController::class, 'withParams'], id: 1, name: 'a'));
59+
60+
$this->assertSame('https://test.com/abc', $router->toUri('/abc'));
5961
}
6062

6163
public function test_with_view(): void

0 commit comments

Comments
 (0)