RunnerLee /
pipeline
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * @author: RunnerLee |
||
| 4 | * @email: [email protected] |
||
| 5 | * @time: 2018-12 |
||
| 6 | */ |
||
| 7 | |||
| 8 | namespace Runner\Pipeline; |
||
| 9 | |||
| 10 | use Runner\Pipeline\Contracts\Pipeline as PipelineInterface; |
||
| 11 | |||
| 12 | class Pipeline implements PipelineInterface |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * @var array |
||
| 16 | */ |
||
| 17 | protected $decorators = []; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @var mixed |
||
| 21 | */ |
||
| 22 | protected $payload; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @var string |
||
| 26 | */ |
||
| 27 | protected $method = 'handle'; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * @param string $payload |
||
| 31 | * |
||
| 32 | * @return $this |
||
| 33 | */ |
||
| 34 | 1 | public function payload($payload) |
|
| 35 | { |
||
| 36 | 1 | $this->payload = $payload; |
|
| 37 | |||
| 38 | 1 | return $this; |
|
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @param $decorator |
||
| 43 | * |
||
| 44 | * @return $this |
||
| 45 | */ |
||
| 46 | 1 | public function pipe($decorator) |
|
| 47 | { |
||
| 48 | 1 | $this->decorators[] = $decorator; |
|
| 49 | |||
| 50 | 1 | return $this; |
|
| 51 | } |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @param $method |
||
| 55 | * |
||
| 56 | * @return $this |
||
| 57 | */ |
||
| 58 | 1 | public function method($method) |
|
| 59 | { |
||
| 60 | 1 | $this->method = $method; |
|
| 61 | |||
| 62 | 1 | return $this; |
|
| 63 | } |
||
| 64 | |||
| 65 | /** |
||
| 66 | * @param null $callback |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 67 | * |
||
| 68 | * @return mixed |
||
| 69 | */ |
||
| 70 | 1 | public function process($callback = null) |
|
| 71 | { |
||
| 72 | 1 | $stage = array_reduce( |
|
| 73 | 1 | array_reverse($this->decorators), |
|
| 74 | 1 | $this->carry(), |
|
| 75 | 1 | new Stage($this->prepareCallback($callback)) |
|
| 76 | ); |
||
| 77 | |||
| 78 | 1 | return $stage->handle($this->payload); |
|
| 79 | } |
||
| 80 | |||
| 81 | /** |
||
| 82 | * @return \Closure |
||
| 83 | */ |
||
| 84 | protected function carry() |
||
| 85 | { |
||
| 86 | 1 | return function ($stage, $decorator) { |
|
| 87 | 1 | return new Stage( |
|
| 88 | 1 | is_callable($decorator) ? $decorator : [$decorator, $this->method], |
|
| 89 | 1 | $stage |
|
| 90 | ); |
||
| 91 | 1 | }; |
|
| 92 | } |
||
| 93 | |||
| 94 | /** |
||
| 95 | * @param callable|null $callback |
||
| 96 | * |
||
| 97 | * @return callable |
||
| 98 | */ |
||
| 99 | 1 | protected function prepareCallback($callback = null) |
|
| 100 | { |
||
| 101 | 1 | if (is_null($callback)) { |
|
| 102 | 1 | $callback = function ($payload) { |
|
| 103 | 1 | return $payload; |
|
| 104 | 1 | }; |
|
| 105 | } |
||
| 106 | |||
| 107 | return $callback; |
||
| 108 | } |
||
| 109 | } |
||
| 110 |