Completed
Pull Request — master (#7)
by Franz
02:14
created

PathDispatcher::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 2
crap 3
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 5
    public function __construct(array $middlewares, Container $container = null)
23
    {
24 5
        $this->middlewares = $middlewares;
25 5
        $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 5
        krsort($this->middlewares);
31 5
    }
32
33 5
    public function process(Request $request, Handler $handler): Response
34
    {
35 5
        $requestPath = $this->getNormalizedPath($request);
36
37 5
        foreach ($this->middlewares as $pathPrefix => $middleware) {
38 5
            if (strpos($requestPath, $pathPrefix) === 0) {
39 4
                return $this->resolve($middleware)
40 4
                    ->process(
41 4
                        $this->unprefixedRequest($request, $pathPrefix),
42 5
                        $this->prefixedHandler($handler, $pathPrefix)
43
                    );
44
            }
45
        }
46
47 1
        return $handler->handle($request);
48
    }
49
50 4
    private function unprefixedRequest(Request $request, string $prefix): Request
51
    {
52 4
        $uri = $request->getUri();
53 4
        return $request->withUri(
54 4
            $uri->withPath(
55 4
                substr($uri->getPath(), strlen($prefix))
56
            )
57
        );
58
    }
59
60 4
    private function prefixedHandler(Handler $handler, string $prefix): Handler
61
    {
62 4
        return new PathPrefixingHandler($handler, $prefix);
63
    }
64
65 5
    private function getNormalizedPath(Request $request): string
66
    {
67 5
        $path = $request->getUri()->getPath();
68 5
        if (empty($path)) {
69
            $path = '/';
70
        }
71
72 5
        return $path;
73
    }
74
}
75