Skip to content

Commit

Permalink
Adds API version verification (#28)
Browse files Browse the repository at this point in the history
* Adds API version verification

Adds a check to the package middleware to ensure that the request
and response version are defined in the configuration.

* Keep ability to pass no versions in the request
  • Loading branch information
sixlive authored and tomschlick committed Aug 23, 2017
1 parent 6460813 commit 5d41e07
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/RequestMigrationsMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class RequestMigrationsMiddleware
{
Expand All @@ -17,6 +18,14 @@ class RequestMigrationsMiddleware
*/
public function handle(Request $request, Closure $next) : Response
{
if ($this->requestVersion($request) && ! in_array($this->requestVersion($request), $this->versions())) {
throw new HttpException(400, 'The request version is invalid');
}

if ($this->responseVersion($request) && ! in_array($this->responseVersion($request), $this->versions())) {
throw new HttpException(400, 'The response version is invalid');
}

$migrator = new Migrator($request, Config::get('request-migrations'));

$migrator->processResponseMigrations(
Expand All @@ -27,4 +36,38 @@ public function handle(Request $request, Closure $next) : Response

return $migrator->getResponse();
}

/**
* Get all the available versions.
*
* @return array
*/
private function versions() : array
{
return array_keys(Config::get('request-migrations.versions'));
}

/**
* Get the request version from the request.
*
* @param \Illuminate\Http\Request $request
*
* @return string
*/
private function requestVersion(Request $request) : string
{
return $request->header(Config::get('request-migrations.headers.request-version'), '');
}

/**
* Get the response version from the request.
*
* @param \Illuminate\Http\Request $request
*
* @return string
*/
private function responseVersion(Request $request) : string
{
return $request->header(Config::get('request-migrations.headers.response-version'), '');
}
}

0 comments on commit 5d41e07

Please sign in to comment.