From 2d5d3a057d0e5157ed406c050715e2e1fec3bad0 Mon Sep 17 00:00:00 2001 From: Jason Lewis Date: Mon, 28 Apr 2014 23:27:45 +1000 Subject: [PATCH] Router gracefully falls back to default API version if no exact matching collection is found. Signed-off-by: Jason Lewis --- src/Routing/Router.php | 15 ++++++++++++++- tests/RoutingRouterTest.php | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Routing/Router.php b/src/Routing/Router.php index a1d95ec50..ef1a6d22f 100644 --- a/src/Routing/Router.php +++ b/src/Routing/Router.php @@ -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; } /** diff --git a/tests/RoutingRouterTest.php b/tests/RoutingRouterTest.php index 85dd97226..7189d776e 100644 --- a/tests/RoutingRouterTest.php +++ b/tests/RoutingRouterTest.php @@ -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()); + } + + }