-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPipeline.php
More file actions
107 lines (92 loc) · 2.64 KB
/
Pipeline.php
File metadata and controls
107 lines (92 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/*
* Opulence
*
* @link https://www.opulencephp.com
* @copyright Copyright (C) 2021 David Young
* @license https://github.com/opulencephp/Opulence/blob/1.2/LICENSE.md
*/
namespace Opulence\Pipelines;
use Closure;
/**
* Defines the pipeline
*/
class Pipeline implements IPipeline
{
/** @var mixed The input to send through the pipeline */
private $input = null;
/** @var array The list of stages to send input through */
private $stages = [];
/** @var string The method to call if the stages are not closures */
private $methodToCall = null;
/** @var callable The callback to execute at the end */
private $callback = null;
/**
* @inheritdoc
*/
public function execute()
{
return call_user_func(
array_reduce(
array_reverse($this->stages),
$this->createStageCallback(),
function ($input) {
if ($this->callback === null) {
return $input;
}
return ($this->callback)($input);
}
),
$this->input
);
}
/**
* @inheritdoc
*/
public function send($input) : IPipeline
{
$this->input = $input;
return $this;
}
/**
* @inheritdoc
*/
public function then(callable $callback) : IPipeline
{
$this->callback = $callback;
return $this;
}
/**
* @inheritdoc
*/
public function through(array $stages, string $methodToCall = null) : IPipeline
{
$this->stages = $stages;
$this->methodToCall = $methodToCall;
return $this;
}
/**
* Creates a callback for an individual stage
*
* @return Closure The callback
* @throws PipelineException Thrown if there was a problem creating a stage
*/
private function createStageCallback() : Closure
{
return function ($stages, $stage) {
return function ($input) use ($stages, $stage) {
if ($stage instanceof Closure) {
return $stage($input, $stages);
} else {
if ($this->methodToCall === null) {
throw new PipelineException('Method must not be null');
}
if (!method_exists($stage, $this->methodToCall)) {
throw new PipelineException(get_class($stage) . "::{$this->methodToCall} does not exist");
}
return $stage->{$this->methodToCall}($input, $stages);
}
};
};
}
}