Skip to content

Commit 2d5d3a0

Browse files
committed
Router gracefully falls back to default API version if no exact matching collection is found.
Signed-off-by: Jason Lewis <jason.lewis1991@gmail.com>
1 parent 12054a2 commit 2d5d3a0

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/Routing/Router.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,20 @@ protected function parseAcceptHeader($request)
449449
*/
450450
public function getApiRouteCollectionFromRequest(Request $request)
451451
{
452-
return array_first($this->api, function($k, $c) use ($request) { return $c->matchesRequest($request); }, null);
452+
$collection = array_first($this->api, function($key, $collection) use ($request)
453+
{
454+
return $collection->matchesRequest($request);
455+
});
456+
457+
// If we don't initially find a collection then we'll grab the default
458+
// version collection instead. This is a sort of graceful fallback
459+
// and allows viewing of the latest API version in the browser.
460+
if ( ! $collection)
461+
{
462+
return $this->getApiRouteCollection($this->defaultVersion);
463+
}
464+
465+
return $collection;
453466
}
454467

455468
/**

tests/RoutingRouterTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,4 +404,25 @@ public function testApiCollectionsWithPointReleaseVersions()
404404
}
405405

406406

407+
public function testRouterDefaultsToDefaultVersionCollectionWhenNoAcceptHeader()
408+
{
409+
$this->router->api(['version' => 'v1', 'prefix' => 'api'], function()
410+
{
411+
$this->router->get('foo', function() { return 'bar'; });
412+
});
413+
414+
$this->router->api(['version' => 'v2', 'prefix' => 'api'], function()
415+
{
416+
$this->router->get('foo', function() { return 'baz'; });
417+
});
418+
419+
$request = Request::create('api/foo', 'GET');
420+
421+
$this->assertEquals('{"message":"bar"}', $this->router->dispatch($request)->getContent());
422+
423+
$this->router->setDefaultVersion('v2');
424+
$this->assertEquals('{"message":"baz"}', $this->router->dispatch($request)->getContent());
425+
}
426+
427+
407428
}

0 commit comments

Comments
 (0)