Completed
Pull Request — master (#7)
by Franz
04:42
created

PathDispatcher::getNormalizedPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 5
cp 0.8
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2.032
1
<?php
2
declare(strict_types=1);
3
4
namespace Northwoods\Broker;
5
6
use Psr\Http\Message\ResponseInterface as Response;
7
use Psr\Http\Message\ServerRequestInterface as Request;
8
use Psr\Http\Server\MiddlewareInterface as Middleware;
9
use Psr\Http\Server\RequestHandlerInterface as Handler;
10
11
class PathDispatcher implements Middleware
12
{
13
    /** @var array */
14
    private $middlewares;
15
16
    /** @var MiddlewareResolver */
17
    private $resolver;
18
19 5
    public function __construct(array $middlewares, MiddlewareResolver $resolver)
20
    {
21 5
        $this->middlewares = $middlewares;
22 5
        $this->resolver = $resolver;
23
24
        // Make sure the longest path prefixes are matched first
25
        // (otherwise, a path /foo would always match, even when /foo/bar
26
        // should match).
27 5
        krsort($this->middlewares);
28 5
    }
29
30 5
    public function process(Request $request, Handler $handler): Response
31
    {
32 5
        $requestPath = $this->getNormalizedPath($request);
33
34 5
        foreach ($this->middlewares as $pathPrefix => $middleware) {
35 5
            if (strpos($requestPath, $pathPrefix) === 0) {
36 4
                return $this->resolver->resolve($middleware)
37 4
                    ->process(
38 4
                        $this->unprefixedRequest($request, $pathPrefix),
39 5
                        $this->prefixedHandler($handler, $pathPrefix)
40
                    );
41
            }
42
        }
43
44 1
        return $handler->handle($request);
45
    }
46
47 4
    private function unprefixedRequest(Request $request, $prefix): Request
48
    {
49 4
        $uri = $request->getUri();
50 4
        return $request->withUri(
51 4
            $uri->withPath(
52 4
                substr($uri->getPath(), strlen($prefix))
53
            )
54
        );
55
    }
56
57 4
    private function prefixedHandler(Handler $handler, $prefix): Handler
58
    {
59 4
        return new PathPrefixingHandler($handler, $prefix);
60
    }
61
62 5
    private function getNormalizedPath(Request $request): string
63
    {
64 5
        $path = $request->getUri()->getPath();
65 5
        if (empty($path)) {
66
            $path = '/';
67
        }
68
69 5
        return $path;
70
    }
71
}
72