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

Broker::resolve()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
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 Broker implements Middleware, MiddlewareResolver
13
{
14
    /** @var Container|null */
15
    private $container;
16
17
    /** @var array */
18
    private $middleware = [];
19
20 9
    public function __construct(Container $container = null)
21
    {
22 9
        $this->container = $container;
23 9
    }
24
25 1
    public function handle(Request $request, callable $default): Response
26
    {
27 1
        $handler = new CallableRequestHandler($default);
28
29 1
        return $this->process($request, $handler);
30
    }
31
32 9
    public function process(Request $request, Handler $handler): Response
33
    {
34 9
        $handler = new RequestHandler($this->middleware, $handler, $this);
35
36 9
        return $handler->handle($request);
37
    }
38
39
    /**
40
     * @param array|string|Middleware $middleware
41
     */
42 4
    public function always($middleware): Broker
43
    {
44 4
        return $this->when($this->alwaysTrue(), $middleware);
45
    }
46
47
    /**
48
     * @param array|string|Middleware $middleware
49
     */
50 4
    public function when(callable $condition, $middleware): Broker
51
    {
52 4
        if (!is_array($middleware)) {
53 3
            $middleware = [$middleware];
54
        }
55
56 4
        foreach ($middleware as $mw) {
57 4
            $this->middleware[] = [$condition, $mw];
58
        }
59
60 4
        return $this;
61
    }
62
63 5
    public function paths(array $paths): Broker
64
    {
65 5
        $this->middleware[] = [
66 5
            $this->alwaysTrue(),
67 5
            new PathDispatcher($paths, $this)
68
        ];
69
70 5
        return $this;
71
    }
72
73 8
    public function resolve($middleware): Middleware
74
    {
75 8
        if ($middleware instanceof Middleware) {
76 7
            return $middleware;
77
        }
78
79 2
        return $this->container->get($middleware);
80
    }
81
82
    private function alwaysTrue(): callable
83
    {
84 8
        return static function () {
85 8
            return true;
86 8
        };
87
    }
88
}
89