Completed
Pull Request — master (#136)
by Alejandro
03:11
created

PathVersionMiddleware::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 3
dl 0
loc 18
ccs 9
cts 9
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Middleware;
5
6
use Interop\Http\ServerMiddleware\DelegateInterface;
7
use Interop\Http\ServerMiddleware\MiddlewareInterface;
8
use Psr\Http\Message\ResponseInterface as Response;
9
use Psr\Http\Message\ServerRequestInterface as Request;
10
11
class PathVersionMiddleware implements MiddlewareInterface
12
{
13
    /**
14
     * Process an incoming server request and return a response, optionally delegating
15
     * to the next middleware component to create the response.
16
     *
17
     * @param Request $request
18
     * @param DelegateInterface $delegate
19
     *
20
     * @return Response
21
     */
22 3
    public function process(Request $request, DelegateInterface $delegate)
23
    {
24 3
        $uri = $request->getUri();
25 3
        $path = $uri->getPath();
26
27
        // TODO Workaround... Do not process the request if it does not start with rest
28 3
        if (\strpos($path, '/rest') !== 0) {
29 1
            return $delegate->process($request);
30
        }
31
32
        // If the path does not begin with the version number, prepend v1 by default for BC compatibility purposes
33 2
        if (\strpos($path, '/rest/v') !== 0) {
34 1
            $parts = \explode('/', $path);
35
            // Remove the first empty part and the rest part
36 1
            \array_shift($parts);
37 1
            \array_shift($parts);
38
            // Prepend the version prefix
39 1
            \array_unshift($parts, '/rest/v1');
40
41 1
            $request = $request->withUri($uri->withPath(\implode('/', $parts)));
42
        }
43
44 2
        return $delegate->process($request);
45
    }
46
}
47