1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Imanghafoori\HeyMan\Reactions; |
4
|
|
|
|
5
|
|
|
use Imanghafoori\HeyMan\ChainManager; |
6
|
|
|
|
7
|
|
|
final class ReactionFactory |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @return \Closure |
11
|
|
|
*/ |
12
|
96 |
|
public function make(): \Closure |
13
|
|
|
{ |
14
|
96 |
|
$reaction = $this->makeReaction(); |
15
|
96 |
|
$condition = resolve(ChainManager::class)->get('condition'); |
16
|
|
|
|
17
|
96 |
|
return function (...$f) use ($condition, $reaction) { |
18
|
67 |
|
if (!$condition($f)) { |
19
|
56 |
|
$reaction(); |
20
|
|
|
} |
21
|
96 |
|
}; |
22
|
|
|
} |
23
|
|
|
|
24
|
96 |
|
private function makeReaction(): \Closure |
25
|
|
|
{ |
26
|
96 |
|
$chain = resolve(ChainManager::class); |
27
|
|
|
|
28
|
96 |
|
$beforeReaction = $this->makePreResponseActions($chain); |
29
|
|
|
|
30
|
96 |
|
$debug = $chain->get('debugInfo'); |
31
|
96 |
|
$termination = $chain->get('termination'); |
32
|
|
|
|
33
|
96 |
|
$responder = resolve(ResponderFactory::class)->make(); |
34
|
|
|
|
35
|
96 |
|
return function () use ($beforeReaction, $responder, $debug, $termination) { |
36
|
56 |
|
if ($termination) { |
37
|
1 |
|
app()->terminating($termination); |
|
|
|
|
38
|
|
|
} |
39
|
56 |
|
event('heyman_reaction_is_happening', $debug); |
40
|
56 |
|
$beforeReaction(); |
41
|
55 |
|
$responder(); |
42
|
96 |
|
}; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param $chain |
47
|
|
|
* |
48
|
|
|
* @return \Closure |
49
|
|
|
*/ |
50
|
96 |
|
private function makePreResponseActions($chain): \Closure |
51
|
|
|
{ |
52
|
96 |
|
$tasks = $this->convertToClosures($chain); |
53
|
96 |
|
$beforeReaction = function () use ($tasks) { |
54
|
56 |
|
foreach ($tasks as $task) { |
55
|
3 |
|
$task(); |
56
|
|
|
} |
57
|
96 |
|
}; |
58
|
|
|
|
59
|
96 |
|
return $beforeReaction; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param $chain |
64
|
|
|
* |
65
|
|
|
* @return array |
66
|
|
|
*/ |
67
|
96 |
|
private function convertToClosures($chain): array |
68
|
|
|
{ |
69
|
96 |
|
$tasks = $chain->get('beforeReaction'); |
70
|
96 |
|
$r = []; |
71
|
96 |
|
foreach ($tasks as $task) { |
72
|
3 |
|
if ($task[1] == 'event') { |
73
|
1 |
|
$r[] = function () use ($task) { |
74
|
1 |
|
resolve('events')->dispatch(...$task[0]); |
|
|
|
|
75
|
1 |
|
}; |
76
|
2 |
|
} elseif ($task[1] == 'cb') { |
77
|
3 |
|
$r[] = function () use ($task) { |
78
|
2 |
|
app()->call(...$task[0]); |
|
|
|
|
79
|
3 |
|
}; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
96 |
|
return $r; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|