Completed
Push — master ( 05e0c3...5b810f )
by Woody
02:35
created

Handler::handle()   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
3
namespace Equip\Dispatch;
4
5
use Interop\Http\Server\RequestHandlerInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
9
class Handler implements RequestHandlerInterface
10
{
11
    /**
12
     * @var array
13
     */
14
    private $middleware;
15
16
    /**
17
     * @var callable
18
     */
19
    private $default;
20
21
    /**
22
     * @var integer
23
     */
24
    private $index = 0;
25
26
    /**
27
     * @param array $middleware
28
     * @param callable $default
29
     */
30 4
    public function __construct(array $middleware, callable $default)
31
    {
32 4
        $this->middleware = $middleware;
33 4
        $this->default = $default;
34 4
    }
35
36
    /**
37
     * Process the request using the current middleware.
38
     *
39
     * @param ServerRequestInterface $request
40
     *
41
     * @return ResponseInterface
42
     */
43 4
    public function handle(ServerRequestInterface $request)
44
    {
45 4
        if (empty($this->middleware[$this->index])) {
46 4
            return call_user_func($this->default, $request);
47
        }
48
49 2
        return $this->middleware[$this->index]->process($request, $this->nextHandler());
50
    }
51
52
    /**
53
     * Get a handler pointing to the next middleware.
54
     *
55
     * @return static
56
     */
57 2
    private function nextHandler()
58
    {
59 2
        $copy = clone $this;
60 2
        $copy->index++;
61
62 2
        return $copy;
63
    }
64
}
65