Completed
Push — master ( 913926...597557 )
by Denis
02:01
created

Chain::createBase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace PhpJsonRpc\Common\Chain;
4
5
/**
6
 * Based on "Chain of Responsibility" pattern
7
 */
8
class Chain
9
{
10
    /**
11
     * @var Chain
12
     */
13
    private $next;
14
15
    /**
16
     * @var callable
17
     */
18
    private $callback;
19
20
    /**
21
     * Chain constructor.
22
     */
23
    private function __construct()
24
    {
25
        $this->next     = null;
26
        $this->callback = null;
27
    }
28
29
    /**
30
     * @return Chain
31
     */
32
    public static function createBase(): Chain
33
    {
34
        return new Chain();
35
    }
36
37
    /**
38
     * @param callable $callback
39
     *
40
     * @return Chain
41
     */
42
    public static function createWith(callable $callback): Chain
43
    {
44
        $element = new Chain();
45
        $element->callback = $callback;
46
47
        return $element;
48
    }
49
50
    /**
51
     * @param Chain $element
52
     *
53
     * @return $this
54
     */
55
    public function add(Chain $element)
56
    {
57
        if ($this->next) {
58
            $this->next->add($element);
59
        } else {
60
            $this->next = $element;
61
        }
62
63
        return $this;
64
    }
65
66
    /**
67
     * @param Container $container
68
     *
69
     * @return mixed
70
     */
71
    public function handle(Container $container): Container
72
    {
73
        // Execute callback and pass result next chain
74
        if (is_callable($this->callback)) {
75
            $result = call_user_func($this->callback, $container);
76
77
            if (!$this->next) {
78
                return $result;
79
            }
80
81
            return $this->next->handle($result);
82
        }
83
84
        // End of chain
85
        if (!$this->next) {
86
            return $container;
87
        }
88
89
        // Execute next chain
90
        return $this->next->handle($container);
91
    }
92
}
93