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