Skip to content

Commit b7c67b9

Browse files
committed
Validate route methods before registration
1 parent c0ba6b5 commit b7c67b9

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/Http/Http.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,14 @@ public static function routes(string|array $methods, string $url): Route
238238
throw new \Exception('At least one HTTP method is required.');
239239
}
240240

241+
$routes = Router::getRoutes();
242+
243+
foreach ($methods as $method) {
244+
if (!\array_key_exists($method, $routes)) {
245+
throw new \Exception("Method ({$method}) not supported.");
246+
}
247+
}
248+
241249
$route = new Route($methods[0], $url, \array_slice($methods, 1));
242250
Router::addRoute($route);
243251

tests/RouterTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,24 @@ public function testCannotRegisterRouteForUnknownMethod(): void
219219
Http::routes([Http::REQUEST_METHOD_GET, 'TRACE'], '/userinfo');
220220
}
221221

222+
public function testUnknownMethodDoesNotPartiallyRegisterRoute(): void
223+
{
224+
try {
225+
Http::routes([Http::REQUEST_METHOD_GET, 'TRACE'], '/userinfo');
226+
$this->fail('Expected unknown method exception.');
227+
} catch (\Exception $exception) {
228+
$this->assertSame('Method (TRACE) not supported.', $exception->getMessage());
229+
}
230+
231+
$routes = Router::getRoutes();
232+
$this->assertArrayNotHasKey('userinfo', $routes[Http::REQUEST_METHOD_GET]);
233+
234+
$route = Http::routes([Http::REQUEST_METHOD_GET, Http::REQUEST_METHOD_POST], '/userinfo');
235+
236+
$this->assertEquals($route, Router::match(Http::REQUEST_METHOD_GET, '/userinfo')?->route);
237+
$this->assertEquals($route, Router::match(Http::REQUEST_METHOD_POST, '/userinfo')?->route);
238+
}
239+
222240
public function testCannotRegisterRouteWithoutMethods(): void
223241
{
224242
$this->expectException(\Exception::class);

0 commit comments

Comments
 (0)