|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PipePassage; |
|
4
|
|
|
|
|
5
|
|
|
class Pipe |
|
6
|
|
|
{ |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Collection of sections. |
|
10
|
|
|
* |
|
11
|
|
|
* @var array |
|
12
|
|
|
*/ |
|
13
|
|
|
protected array $sections = []; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Section key. |
|
17
|
|
|
* |
|
18
|
|
|
* @var int |
|
19
|
|
|
*/ |
|
20
|
|
|
protected int $currentSectionKey = 0; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param array $sections |
|
24
|
|
|
*/ |
|
25
|
2 |
|
public function __construct(array $sections = []) |
|
26
|
|
|
{ |
|
27
|
2 |
|
foreach ($sections as $section) { |
|
28
|
1 |
|
$this->next($section); |
|
29
|
|
|
} |
|
30
|
2 |
|
} |
|
31
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Static initialisation helper. |
|
35
|
|
|
* |
|
36
|
|
|
* @return static |
|
37
|
|
|
*/ |
|
38
|
2 |
|
public static function make(...$arguments): static |
|
39
|
|
|
{ |
|
40
|
2 |
|
return new static(...$arguments); |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Add next section to pipe. |
|
45
|
|
|
* |
|
46
|
|
|
* @param $section |
|
47
|
|
|
* |
|
48
|
|
|
* @return $this |
|
49
|
|
|
*/ |
|
50
|
1 |
|
public function next($section): static |
|
51
|
|
|
{ |
|
52
|
1 |
|
$this->sections[] = $section; |
|
53
|
|
|
|
|
54
|
1 |
|
return $this; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param object $entity |
|
59
|
|
|
* |
|
60
|
|
|
* @return object |
|
61
|
|
|
*/ |
|
62
|
2 |
|
public function pass(object $entity): object |
|
63
|
|
|
{ |
|
64
|
2 |
|
if (empty($this->sections)) { |
|
65
|
1 |
|
return $entity; |
|
66
|
|
|
} |
|
67
|
1 |
|
$this->currentSectionKey = -1; |
|
68
|
|
|
|
|
69
|
1 |
|
$next = $this->createCallback(); |
|
70
|
1 |
|
$next($entity); |
|
71
|
|
|
|
|
72
|
1 |
|
return $entity; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @return \Closure |
|
77
|
|
|
*/ |
|
78
|
1 |
|
protected function createCallback(): \Closure |
|
79
|
|
|
{ |
|
80
|
1 |
|
$this->currentSectionKey++; |
|
81
|
1 |
|
$handler = $this->sections[ $this->currentSectionKey ] ?? null; |
|
82
|
|
|
|
|
83
|
1 |
|
return function ($entity) use ($handler) { |
|
84
|
1 |
|
if ($handler instanceof PipeSection) { |
|
85
|
1 |
|
return call_user_func([ $handler, 'handle' ], $entity, $this->createCallback()); |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
1 |
|
if (is_string($handler) && is_a($handler, PipeSection::class, true)) { |
|
89
|
1 |
|
return call_user_func([ new $handler(), 'handle' ], $entity, $this->createCallback()); |
|
90
|
|
|
} |
|
91
|
|
|
|
|
92
|
1 |
|
if (is_callable($handler)) { |
|
93
|
1 |
|
return call_user_func($handler, $entity, $this->createCallback()); |
|
94
|
|
|
} |
|
95
|
|
|
|
|
96
|
1 |
|
return $entity; |
|
97
|
1 |
|
}; |
|
98
|
|
|
} |
|
99
|
|
|
} |
|
100
|
|
|
|