1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Phuria\Pipolino; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* This file is part of phuria/pipolino package. |
7
|
|
|
* |
8
|
|
|
* Copyright (c) 2017 Beniamin Jonatan Šimko |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
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
|
6 |
|
public function __construct(array $stages = [], callable $defaultStage = null) |
34
|
|
|
{ |
35
|
6 |
|
$this->stages = $stages; |
36
|
6 |
|
$this->defaultStage = $defaultStage ?: new DefaultStage(); |
37
|
6 |
|
dump($this->defaultStage); |
38
|
6 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param callable $next |
42
|
|
|
* @param array ...$args |
43
|
|
|
* |
44
|
|
|
* @return mixed |
45
|
|
|
*/ |
46
|
1 |
|
public function __invoke(callable $next, ...$args) |
47
|
|
|
{ |
48
|
1 |
|
return $this->process(...$args); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param array ...$args |
53
|
|
|
* |
54
|
|
|
* @return mixed |
55
|
|
|
*/ |
56
|
6 |
|
public function process(...$args) |
57
|
|
|
{ |
58
|
6 |
|
if (0 === count($this->stages)) { |
59
|
6 |
|
return call_user_func($this->defaultStage, ...$args); |
60
|
|
|
} |
61
|
|
|
|
62
|
5 |
|
$stages = $this->stages; |
63
|
5 |
|
$currentStage = array_shift($stages); |
64
|
|
|
|
65
|
5 |
|
$next = function (...$args) use ($stages) { |
66
|
5 |
|
return (new Pipolino($stages, $this->defaultStage))->process(...$args); |
67
|
5 |
|
}; |
68
|
|
|
|
69
|
5 |
|
return call_user_func($currentStage, $next, ...$args); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param callable $stage |
74
|
|
|
* |
75
|
|
|
* @return Pipolino |
76
|
|
|
*/ |
77
|
5 |
|
public function addStage(callable $stage) |
78
|
|
|
{ |
79
|
5 |
|
$stages = $this->stages; |
80
|
5 |
|
$stages[] = $stage; |
81
|
|
|
|
82
|
5 |
|
return new self($stages, $this->defaultStage); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @param callable $stage |
87
|
|
|
* |
88
|
|
|
* @return Pipolino |
89
|
|
|
*/ |
90
|
1 |
|
public function withDefaultStage(callable $stage) |
91
|
|
|
{ |
92
|
1 |
|
return new self($this->stages, $stage); |
93
|
|
|
} |
94
|
|
|
} |