1 | <?php |
||
7 | class Pipeline implements PipelineInterface |
||
8 | { |
||
9 | /** |
||
10 | * @var callable[] |
||
11 | */ |
||
12 | private $stages = []; |
||
13 | |||
14 | /** |
||
15 | * Constructor. |
||
16 | * |
||
17 | * @param callable[] $stages |
||
18 | * |
||
19 | * @throws InvalidArgumentException |
||
20 | */ |
||
21 | 18 | public function __construct(array $stages = []) |
|
22 | { |
||
23 | 18 | foreach ($stages as $stage) { |
|
24 | 6 | if (false === is_callable($stage)) { |
|
25 | 2 | throw new InvalidArgumentException('All stages should be callable.'); |
|
26 | } |
||
27 | 16 | } |
|
28 | |||
29 | 16 | $this->stages = $stages; |
|
30 | 16 | } |
|
31 | |||
32 | /** |
||
33 | * @inheritdoc |
||
34 | */ |
||
35 | 8 | public function pipe(callable $stage) |
|
36 | { |
||
37 | 8 | $pipeline = clone $this; |
|
38 | 8 | $pipeline->stages[] = $stage; |
|
39 | |||
40 | 8 | return $pipeline; |
|
41 | } |
||
42 | |||
43 | /** |
||
44 | * Process the payload. |
||
45 | * |
||
46 | * @param $payload |
||
47 | * |
||
48 | * @return mixed |
||
49 | */ |
||
50 | 10 | public function process($payload) |
|
51 | { |
||
52 | 10 | foreach ($this->stages as $stage) { |
|
53 | 10 | $payload = call_user_func($stage, $payload); |
|
54 | 10 | } |
|
55 | |||
56 | 10 | return $payload; |
|
57 | } |
||
58 | |||
59 | /** |
||
60 | * @inheritdoc |
||
61 | */ |
||
62 | 4 | public function __invoke($payload) |
|
66 | } |
||
67 |