1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of phuria/pipolino package. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2017 Beniamin Jonatan Šimko |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Phuria\Pipolino; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @author Beniamin Jonatan Šimko <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class Pipolino |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
private $stages; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var callable |
26
|
|
|
*/ |
27
|
|
|
private $defaultStage; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param array $stages |
31
|
|
|
* @param callable $defaultStage |
32
|
|
|
* |
33
|
|
|
* @throws InvalidStageException |
34
|
|
|
*/ |
35
|
9 |
|
public function __construct(array $stages = [], callable $defaultStage = null) |
36
|
|
|
{ |
37
|
9 |
|
foreach ($stages as $stage) { |
38
|
8 |
|
if (false === is_callable($stage)) { |
39
|
3 |
|
throw InvalidStageException::create($stage); |
40
|
|
|
} |
41
|
6 |
|
} |
42
|
|
|
|
43
|
6 |
|
$this->stages = $stages; |
44
|
6 |
|
$this->defaultStage = $defaultStage ?: new DefaultStage(); |
45
|
6 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param callable $next |
49
|
|
|
* @param array ...$args |
50
|
|
|
* |
51
|
|
|
* @return mixed |
52
|
|
|
*/ |
53
|
1 |
|
public function __invoke(callable $next, ...$args) |
54
|
|
|
{ |
55
|
1 |
|
return $this->process(...$args); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param array ...$args |
60
|
|
|
* |
61
|
|
|
* @return mixed |
62
|
|
|
*/ |
63
|
6 |
|
public function process(...$args) |
64
|
|
|
{ |
65
|
6 |
|
if (0 === count($this->stages)) { |
66
|
6 |
|
return call_user_func($this->defaultStage, ...$args); |
67
|
|
|
} |
68
|
|
|
|
69
|
5 |
|
$stages = $this->stages; |
70
|
5 |
|
$currentStage = array_shift($stages); |
71
|
|
|
|
72
|
5 |
|
$next = function (...$args) use ($stages) { |
73
|
5 |
|
return (new Pipolino($stages, $this->defaultStage))->process(...$args); |
74
|
5 |
|
}; |
75
|
|
|
|
76
|
5 |
|
return call_user_func($currentStage, $next, ...$args); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @param callable $stage |
81
|
|
|
* |
82
|
|
|
* @return Pipolino |
83
|
|
|
*/ |
84
|
5 |
|
public function addStage(callable $stage) |
85
|
|
|
{ |
86
|
5 |
|
$stages = $this->stages; |
87
|
5 |
|
$stages[] = $stage; |
88
|
|
|
|
89
|
5 |
|
return new self($stages, $this->defaultStage); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* @param callable $stage |
94
|
|
|
* |
95
|
|
|
* @return Pipolino |
96
|
|
|
*/ |
97
|
1 |
|
public function withDefaultStage(callable $stage) |
98
|
|
|
{ |
99
|
1 |
|
return new self($this->stages, $stage); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|