|
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
|
|
|
|