Fixed PathVersionMiddleware not being properly propagated

This commit is contained in:
Alejandro Celaya
2018-03-26 17:53:22 +02:00
parent ee2233c6dd
commit 4d0fc1da07
4 changed files with 34 additions and 8 deletions

View File

@@ -24,13 +24,19 @@ class PathVersionMiddleware implements MiddlewareInterface
$uri = $request->getUri();
$path = $uri->getPath();
// TODO Workaround... Do not process the request if it does not start with rest
if (\strpos($path, '/rest') !== 0) {
return $delegate->process($request);
}
// If the path does not begin with the version number, prepend v1 by default for BC compatibility purposes
if (\strpos($path, '/v') !== 0) {
if (\strpos($path, '/rest/v') !== 0) {
$parts = \explode('/', $path);
// Remove the first empty part and the
// Remove the first empty part and the rest part
\array_shift($parts);
\array_shift($parts);
// Prepend the version prefix
\array_unshift($parts, '/v1');
\array_unshift($parts, '/rest/v1');
$request = $request->withUri($uri->withPath(\implode('/', $parts)));
}

View File

@@ -30,7 +30,22 @@ class PathVersionMiddlewareTest extends TestCase
*/
public function whenVersionIsProvidedRequestRemainsUnchanged()
{
$request = ServerRequestFactory::fromGlobals()->withUri(new Uri('/v2/foo'));
$request = ServerRequestFactory::fromGlobals()->withUri(new Uri('/rest/v2/foo'));
$delegate = $this->prophesize(DelegateInterface::class);
$process = $delegate->process($request)->willReturn(new Response());
$this->middleware->process($request, $delegate->reveal());
$process->shouldHaveBeenCalled();
}
/**
* @test
*/
public function whenPathDoesNotStartWithRestRemainsUnchanged()
{
$request = ServerRequestFactory::fromGlobals()->withUri(new Uri('/foo'));
$delegate = $this->prophesize(DelegateInterface::class);
$process = $delegate->process($request)->willReturn(new Response());
@@ -45,14 +60,14 @@ class PathVersionMiddlewareTest extends TestCase
*/
public function versionOneIsPrependedWhenNoVersionIsDefined()
{
$request = ServerRequestFactory::fromGlobals()->withUri(new Uri('/bar/baz'));
$request = ServerRequestFactory::fromGlobals()->withUri(new Uri('/rest/bar/baz'));
$delegate = $this->prophesize(DelegateInterface::class);
$delegate->process(Argument::type(Request::class))->will(function (array $args) use ($request) {
$req = \array_shift($args);
Assert::assertNotSame($request, $req);
Assert::assertEquals('/v1/bar/baz', $req->getUri()->getPath());
Assert::assertEquals('/rest/v1/bar/baz', $req->getUri()->getPath());
return new Response();
});