Completed
Push — master ( 3d9760...2451d4 )
by Woody
01:20
created

Delegate::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 9
cts 9
cp 1
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Northwoods\Broker;
4
5
use Interop\Http\ServerMiddleware\DelegateInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use SplObjectStorage;
8
9
class Delegate implements DelegateInterface
10
{
11
    /**
12
     * @var SplObjectStorage
13
     */
14
    private $middleware;
15
16
    /**
17
     * @var DelegateInterface $nextDelegate
18
     */
19
    private $nextDelegate;
20
21 4
    public function __construct(SplObjectStorage $middleware, DelegateInterface $nextDelegate)
22
    {
23 4
        $this->middleware = clone $middleware;
24 4
        $this->nextDelegate = $nextDelegate;
25
26
        // Rewind the middleware to the start
27 4
        $this->middleware->rewind();
28 4
    }
29
30
    // DelegateInterface
31 4
    public function process(ServerRequestInterface $request)
32
    {
33
        /** @var MiddlewareInterface */
34 4
        $middleware = $this->middleware->current();
35
36 4
        if (empty($middleware)) {
37 4
            return $this->nextDelegate->process($request);
38
        }
39
40
        /** @var callable */
41 3
        $condition = $this->middleware[$middleware];
42
43
        /** @var DelegateInterface */
44 3
        $delegate = $this->nextDelegate();
45
46 3
        if ($condition($request)) {
47 3
            return $middleware->process($request, $delegate);
48
        } else {
49 1
            return $delegate->process($request);
50
        }
51
    }
52
53
    /**
54
     * @return DelegateInterface
55
     */
56 3
    private function nextDelegate()
57
    {
58 3
        $copy = clone $this;
59 3
        $copy->middleware->next();
60
61 3
        return $copy;
62
    }
63
}
64