Test Failed
Branch master (e46a7e)
by mcfog
02:27
created

MiddlewarePipe::append()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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