Skip to content

Commit 5e1f431

Browse files
bwoebinikic
authored andcommitted
Add fallback routes matching *any* method
These are strictly fallback handlers and only match after all other routes have been tried. The target use case are path-specific 404 pages or similar.
1 parent a383afb commit 5e1f431

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/Dispatcher/RegexBasedAbstract.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@ public function dispatch($httpMethod, $uri) {
3838
}
3939
}
4040

41+
// If nothing else matches, try fallback routes
42+
if (isset($this->staticRouteMap['*'][$uri])) {
43+
$handler = $this->staticRouteMap['*'][$uri];
44+
return [self::FOUND, $handler, []];
45+
}
46+
if (isset($varRouteData['*'])) {
47+
$result = $this->dispatchVariableRoute($varRouteData['*'], $uri);
48+
if ($result[0] === self::FOUND) {
49+
return $result;
50+
}
51+
}
52+
4153
// Find allowed methods for this URI by matching against all other HTTP methods as well
4254
$allowedMethods = [];
4355

test/Dispatcher/DispatcherTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,38 @@ public function provideFoundDispatchCases() {
362362

363363
$cases[] = ['HEAD', '/foo', $callback, 'handler1', ['bar' => 'foo']];
364364

365+
// 20 ----
366+
367+
$callback = function(RouteCollector $r) {
368+
$r->addRoute('*', '/user', 'handler0');
369+
$r->addRoute('*', '/{user}', 'handler1');
370+
$r->addRoute('GET', '/user', 'handler2');
371+
};
372+
373+
$cases[] = ['GET', '/user', $callback, 'handler2', []];
374+
375+
// 21 ----
376+
377+
$callback = function(RouteCollector $r) {
378+
$r->addRoute('*', '/user', 'handler0');
379+
$r->addRoute('GET', '/user', 'handler1');
380+
};
381+
382+
$cases[] = ['POST', '/user', $callback, 'handler0', []];
383+
384+
// 22 ----
385+
386+
$cases[] = ['HEAD', '/user', $callback, 'handler1', []];
387+
388+
// 23 ----
389+
390+
$callback = function(RouteCollector $r) {
391+
$r->addRoute('GET', '/{bar}', 'handler0');
392+
$r->addRoute('*', '/foo', 'handler1');
393+
};
394+
395+
$cases[] = ['GET', '/foo', $callback, 'handler0', ['bar' => 'foo']];
396+
365397
// x -------------------------------------------------------------------------------------->
366398

367399
return $cases;
@@ -464,6 +496,7 @@ public function provideMethodNotAllowedDispatchCases() {
464496
$r->addRoute('GET', '/resource/123/456', 'handler0');
465497
$r->addRoute('POST', '/resource/123/456', 'handler1');
466498
$r->addRoute('PUT', '/resource/123/456', 'handler2');
499+
$r->addRoute('*', '/', 'handler3');
467500
};
468501

469502
$method = 'DELETE';

0 commit comments

Comments
 (0)