Skip to content

Commit

Permalink
Add fallback routes matching *any* method
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bwoebi authored and nikic committed Mar 25, 2016
1 parent a383afb commit 5e1f431
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Dispatcher/RegexBasedAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ public function dispatch($httpMethod, $uri) {
}
}

// If nothing else matches, try fallback routes
if (isset($this->staticRouteMap['*'][$uri])) {
$handler = $this->staticRouteMap['*'][$uri];
return [self::FOUND, $handler, []];
}
if (isset($varRouteData['*'])) {
$result = $this->dispatchVariableRoute($varRouteData['*'], $uri);
if ($result[0] === self::FOUND) {
return $result;
}
}

// Find allowed methods for this URI by matching against all other HTTP methods as well
$allowedMethods = [];

Expand Down
33 changes: 33 additions & 0 deletions test/Dispatcher/DispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,38 @@ public function provideFoundDispatchCases() {

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

// 20 ----

$callback = function(RouteCollector $r) {
$r->addRoute('*', '/user', 'handler0');
$r->addRoute('*', '/{user}', 'handler1');
$r->addRoute('GET', '/user', 'handler2');
};

$cases[] = ['GET', '/user', $callback, 'handler2', []];

// 21 ----

$callback = function(RouteCollector $r) {
$r->addRoute('*', '/user', 'handler0');
$r->addRoute('GET', '/user', 'handler1');
};

$cases[] = ['POST', '/user', $callback, 'handler0', []];

// 22 ----

$cases[] = ['HEAD', '/user', $callback, 'handler1', []];

// 23 ----

$callback = function(RouteCollector $r) {
$r->addRoute('GET', '/{bar}', 'handler0');
$r->addRoute('*', '/foo', 'handler1');
};

$cases[] = ['GET', '/foo', $callback, 'handler0', ['bar' => 'foo']];

// x -------------------------------------------------------------------------------------->

return $cases;
Expand Down Expand Up @@ -464,6 +496,7 @@ public function provideMethodNotAllowedDispatchCases() {
$r->addRoute('GET', '/resource/123/456', 'handler0');
$r->addRoute('POST', '/resource/123/456', 'handler1');
$r->addRoute('PUT', '/resource/123/456', 'handler2');
$r->addRoute('*', '/', 'handler3');
};

$method = 'DELETE';
Expand Down

0 comments on commit 5e1f431

Please sign in to comment.