Completed
Push — master ( 06dd79...66818b )
by Sébastien
02:04
created

Pipeline::setPipes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace Bdf\Pipeline;
4
5
use Bdf\Pipeline\CallableFactory\StackCallableFactory;
6
7
/**
8
 * Pipeline
9
 *
10
 * @author Sébastien Tanneux
11
 */
12
final class Pipeline
13
{
14
    /**
15
     * The callable factory
16
     *
17
     * @var CallableFactoryInterface
18
     */
19
    private $factory;
20
21
    /**
22
     * The pipes
23
     *
24
     * @var callable[]
25
     */
26
    private $pipes = [];
27
28
    /**
29
     * The destination of the last pipe
30
     *
31
     * @var callable
32
     */
33
    private $outlet;
34
35
    /**
36
     * The built callable
37
     *
38
     * @var callable
39
     */
40
    private $callable;
41
42
    /**
43
     * Pipeline constructor.
44
     *
45
     * @param CallableFactoryInterface $factory
46
     */
47
    public function __construct(CallableFactoryInterface $factory = null)
48
    {
49
        $this->factory = $factory ?: new StackCallableFactory();
50
    }
51
52
    /**
53
     * Set the pipes
54
     *
55
     * @param callable[] $pipes
56
     */
57
    public function setPipes(array $pipes)
58
    {
59
        $this->pipes = $pipes;
60
    }
61
62
    /**
63
     * Add a pipe at the beginning of the chain
64
     *
65
     * @param callable $first
66
     */
67
    public function prepend($first)
68
    {
69
        array_unshift($this->pipes, $first);
70
    }
71
72
    /**
73
     * Add a pipe
74
     *
75
     * @param callable $last
76
     */
77
    public function pipe($last)
78
    {
79
        $this->pipes[] = $last;
80
    }
81
82
    /**
83
     * Set the pipeline outlet
84
     *
85
     * @param callable $outlet
86
     */
87
    public function outlet(callable $outlet)
88
    {
89
        $this->outlet = $outlet;
90
    }
91
92
    /**
93
     * Send the payload into the pipeline.
94
     *
95
     * @param array $payload
96
     *
97
     * @return mixed
98
     */
99
    public function send(...$payload)
100
    {
101
        if ($this->callable === null) {
102
            $this->callable = $this->factory->createCallable($this->pipes, $this->outlet);
103
        }
104
105
        $callable = $this->callable;
106
        return $callable(...$payload);
107
    }
108
109
    /**
110
     * Pipeline invokation
111
     *
112
     * @param array $payload
113
     *
114
     * @return mixed
115
     */
116
    public function __invoke(...$payload)
117
    {
118
        // TODO works only with LinkedCallableFactory
119
        return $this->send(...$payload);
120
    }
121
122
    /**
123
     * Clear the callable
124
     */
125
    public function __clone()
126
    {
127
        $this->callable = null;
128
    }
129
}
130