Chain::process()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * This file is part of Zee Project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @see https://github.com/zee/
9
 */
10
11
declare(strict_types=1);
12
13
namespace Zee\Chains;
14
15
/**
16
 * Chain of the responsibility.
17
 */
18
final class Chain implements Handler
19
{
20
    /**
21
     * @var Sequence
22
     */
23
    private $iterator;
24
25
    /**
26
     * @var Stage
27
     */
28
    private $stage;
29
30
    /**
31
     * @var Handler[]
32
     */
33
    private $handlers;
34
35
    /**
36
     * @var int
37
     */
38
    private $count;
39
40
    /**
41
     * Init chain.
42
     */
43 2
    public function __construct()
44
    {
45 2
        $this->handlers = [new NoopHandler()];
46 2
        $this->count = 0;
47 2
        $this->iterator = new Sequence($this);
48 2
        $this->stage = new Stage($this->iterator);
49 2
    }
50
51
    /**
52
     * @param Handler $handler
53
     *
54
     * @return Chain
55
     */
56 2
    public function push(Handler $handler): self
57
    {
58 2
        $this->handlers[] = $handler;
59 2
        ++$this->count;
60
61 2
        return $this;
62
    }
63
64
    /**
65
     * Picks handler by index.
66
     *
67
     * @param int $index
68
     *
69
     * @return Handler
70
     */
71 2
    public function pick(int $index): Handler
72
    {
73 2
        return $this->handlers[($index + 1) * ($index < $this->count)];
74
    }
75
76
    /**
77
     * @param mixed $payload
78
     *
79
     * @return mixed
80
     */
81 2
    public function process($payload)
82
    {
83 2
        $handler = $this->iterator->pickFirst();
84 2
        $payload = $handler->handle($payload, $this->stage);
85
86 2
        return $payload;
87
    }
88
89
    /**
90
     * Allows reuse the chain as handler of the another.
91
     *
92
     * {@inheritdoc}
93
     */
94 1
    public function handle($payload, Stage $next)
95
    {
96 1
        return $next->process($this->process($payload));
97
    }
98
}
99