Completed
Pull Request — master (#7)
by Franz
01:26
created

PathDispatcher::unprefixedRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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