Completed
Push — master ( 6eef69...27b08f )
by Alejandro
07:50
created

PathVersionMiddleware   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 2
lcom 0
cbo 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 19 2
1
<?php
2
namespace Shlinkio\Shlink\Rest\Middleware;
3
4
use Psr\Http\Message\ResponseInterface as Response;
5
use Psr\Http\Message\ServerRequestInterface as Request;
6
use Zend\Stratigility\MiddlewareInterface;
7
8
class PathVersionMiddleware implements MiddlewareInterface
9
{
10
    /**
11
     * Process an incoming request and/or response.
12
     *
13
     * Accepts a server-side request and a response instance, and does
14
     * something with them.
15
     *
16
     * If the response is not complete and/or further processing would not
17
     * interfere with the work done in the middleware, or if the middleware
18
     * wants to delegate to another process, it can use the `$out` callable
19
     * if present.
20
     *
21
     * If the middleware does not return a value, execution of the current
22
     * request is considered complete, and the response instance provided will
23
     * be considered the response to return.
24
     *
25
     * Alternately, the middleware may return a response instance.
26
     *
27
     * Often, middleware will `return $out();`, with the assumption that a
28
     * later middleware will return a response.
29
     *
30
     * @param Request $request
31
     * @param Response $response
32
     * @param null|callable $out
33
     * @return null|Response
34
     */
35
    public function __invoke(Request $request, Response $response, callable $out = null)
36
    {
37
        $uri = $request->getUri();
38
        $path = $uri->getPath();
39
40
        // If the path does not begin with the version number, prepend v1 by default for retrocompatibility purposes
41
        if (strpos($path, '/rest/v') !== 0) {
42
            $parts = explode('/', $path);
43
            // Remove the first empty part and the "/rest" prefix
44
            array_shift($parts);
45
            array_shift($parts);
46
            // Prepend the prefix with version
47
            array_unshift($parts, '/rest/v1');
48
49
            $request = $request->withUri($uri->withPath(implode('/', $parts)));
50
        }
51
52
        return $out($request, $response);
53
    }
54
}
55