Passed
Push — master ( b6a195...1e79f7 )
by mcfog
03:21
created

MiddlewarePipe   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 15
dl 0
loc 66
c 0
b 0
f 0
ccs 17
cts 17
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A append() 0 4 1
A __construct() 0 4 1
A prepend() 0 4 1
A loop() 0 7 2
A main() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lit\Nimo\Middlewares;
6
7
use Lit\Nimo\Handlers\CallableHandler;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
13
class MiddlewarePipe extends AbstractMiddleware
14
{
15
    /**
16
     * @var RequestHandlerInterface
17
     */
18
    protected $nextHandler;
19
    /**
20
     * @var MiddlewareInterface[]
21
     */
22
    protected $stack = [];
23
    protected $index;
24
25 3
    public function __construct()
26
    {
27
        $this->nextHandler = CallableHandler::wrap(function (ServerRequestInterface $request) {
28 2
            return $this->loop($request);
29 3
        });
30 3
    }
31
32
33
    /**
34
     * append $middleware
35
     * return $this
36
     * note this method would modify $this
37
     *
38
     * @param MiddlewareInterface $middleware
39
     * @return $this
40
     */
41 1
    public function append(MiddlewareInterface $middleware): MiddlewarePipe
42
    {
43 1
        $this->stack[] = $middleware;
44 1
        return $this;
45
    }
46
47
    /**
48
     * prepend $middleware
49
     * return $this
50
     * note this method would modify $this
51
     *
52
     * @param MiddlewareInterface $middleware
53
     * @return $this
54
     */
55 1
    public function prepend(MiddlewareInterface $middleware): MiddlewarePipe
56
    {
57 1
        array_unshift($this->stack, $middleware);
58 1
        return $this;
59
    }
60
61 3
    protected function main(): ResponseInterface
62
    {
63 3
        $this->index = 0;
64
65 3
        return $this->loop($this->request);
66
    }
67
68
    /**
69
     * @param ServerRequestInterface $request
70
     * @return ResponseInterface
71
     */
72 3
    protected function loop(ServerRequestInterface $request): ResponseInterface
73
    {
74 3
        if (!isset($this->stack[$this->index])) {
75 3
            return $this->delegate($request);
76
        }
77
78 2
        return $this->stack[$this->index++]->process($request, $this->nextHandler);
79
    }
80
}
81