Skip to content

Commit

Permalink
Router gracefully falls back to default API version if no exact match…
Browse files Browse the repository at this point in the history
…ing collection is found.

Signed-off-by: Jason Lewis <jason.lewis1991@gmail.com>
  • Loading branch information
jasonlewis committed Apr 28, 2014
1 parent 12054a2 commit 2d5d3a0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,20 @@ protected function parseAcceptHeader($request)
*/
public function getApiRouteCollectionFromRequest(Request $request)
{
return array_first($this->api, function($k, $c) use ($request) { return $c->matchesRequest($request); }, null);
$collection = array_first($this->api, function($key, $collection) use ($request)
{
return $collection->matchesRequest($request);
});

// If we don't initially find a collection then we'll grab the default
// version collection instead. This is a sort of graceful fallback
// and allows viewing of the latest API version in the browser.
if ( ! $collection)
{
return $this->getApiRouteCollection($this->defaultVersion);
}

return $collection;
}

/**
Expand Down
21 changes: 21 additions & 0 deletions tests/RoutingRouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,4 +404,25 @@ public function testApiCollectionsWithPointReleaseVersions()
}


public function testRouterDefaultsToDefaultVersionCollectionWhenNoAcceptHeader()
{
$this->router->api(['version' => 'v1', 'prefix' => 'api'], function()
{
$this->router->get('foo', function() { return 'bar'; });
});

$this->router->api(['version' => 'v2', 'prefix' => 'api'], function()
{
$this->router->get('foo', function() { return 'baz'; });
});

$request = Request::create('api/foo', 'GET');

$this->assertEquals('{"message":"bar"}', $this->router->dispatch($request)->getContent());

$this->router->setDefaultVersion('v2');
$this->assertEquals('{"message":"baz"}', $this->router->dispatch($request)->getContent());
}


}

0 comments on commit 2d5d3a0

Please sign in to comment.