Rename::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
8
/**
9
 * Middleware to rename the uri path.
10
 */
11
class Rename
12
{
13
    /**
14
     * @var array Renamed paths
15
     */
16
    private $paths;
17
18
    /**
19
     * Constructor. Set the paths.
20
     *
21
     * @param array $paths ['real-name' => 'new-name']
22
     */
23
    public function __construct(array $paths)
24
    {
25
        $this->paths = $paths;
26
    }
27
28
    /**
29
     * Execute the middleware.
30
     *
31
     * @param RequestInterface  $request
32
     * @param ResponseInterface $response
33
     * @param callable          $next
34
     *
35
     * @return ResponseInterface
36
     */
37
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
38
    {
39
        $uri = $request->getUri();
40
        $path = $uri->getPath();
41
42
        if (isset($this->paths[$path])) {
43
            return $response->withStatus(404);
44
        }
45
46
        $newPath = array_search($path, $this->paths, true);
47
48
        if ($newPath !== false) {
49
            $request = $request->withUri($uri->withPath($newPath));
50
        }
51
52
        return $next($request, $response);
53
    }
54
}
55