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

PathDispatcher   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 96.15%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 6
dl 0
loc 63
ccs 25
cts 26
cp 0.9615
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A process() 0 16 3
A unprefixedRequest() 0 9 1
A prefixedHandler() 0 4 1
A getNormalizedPath() 0 9 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 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