Completed
Push — master ( 7dba56...6875ae )
by Oscar
10:21
created

Rename::paths()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4286
cc 1
eloc 3
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|null $paths
22
     */
23
    public function __construct(array $paths = null)
24
    {
25
        if ($paths !== null) {
26
            $this->paths($paths);
27
        }
28
    }
29
30
    /**
31
     * Map with the names.
32
     *
33
     * @param array $paths ['private-name' => 'public-name']
34
     *
35
     * @return self
36
     */
37
    public function paths(array $paths)
38
    {
39
        $this->paths = $paths;
40
41
        return $this;
42
    }
43
44
    /**
45
     * Execute the middleware.
46
     *
47
     * @param RequestInterface  $request
48
     * @param ResponseInterface $response
49
     * @param callable          $next
50
     *
51
     * @return ResponseInterface
52
     */
53
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
54
    {
55
        $uri = $request->getUri();
56
        $path = $uri->getPath();
57
58
        if (isset($this->paths[$path])) {
59
            return $response->withStatus(404);
60
        }
61
62
        $newPath = array_search($path, $this->paths, true);
63
64
        if ($newPath !== false) {
65
            $request = $request->withUri($uri->withPath($newPath));
66
        }
67
68
        return $next($request, $response);
69
    }
70
}
71