1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Contains the Hooks class. |
7
|
|
|
* |
8
|
|
|
* @copyright Copyright (c) 2021 Attila Fulop |
9
|
|
|
* @author Attila Fulop |
10
|
|
|
* @license MIT |
11
|
|
|
* @since 2021-11-19 |
12
|
|
|
* |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace Konekt\Concord\Hooks; |
16
|
|
|
|
17
|
|
|
use Illuminate\Support\Collection; |
18
|
|
|
|
19
|
|
|
final class Hooks |
20
|
|
|
{ |
21
|
|
|
private Collection $hooks; |
22
|
|
|
|
23
|
|
|
public function __construct() |
24
|
|
|
{ |
25
|
|
|
$this->hooks = collect(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function register(HookEvent $event, callable $callback, array|string $filter = null): void |
29
|
|
|
{ |
30
|
|
|
/** @var array{event: HookEvent, callback: callable, filter: string|array|null} */ |
31
|
|
|
$hook = [ |
32
|
|
|
'event' => $event, |
33
|
|
|
'callback' => $callback, |
34
|
|
|
'filter' => $filter, |
35
|
|
|
]; |
36
|
|
|
|
37
|
|
|
$this->hooks->add($hook); |
38
|
|
|
dump('r', $this->hooks->all()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function happening(HookEvent $event, string $moduleId, mixed $hookableArgument): mixed |
42
|
|
|
{ |
43
|
|
|
dump('h', $this->hooks->all()); |
44
|
|
|
$hooks = $this->hooks->filter( |
45
|
|
|
fn ($hook, $index) => $event->equals($hook['event']) && $this->theHookIsForTheModule($hook['filter'], $moduleId) |
|
|
|
|
46
|
|
|
); |
47
|
|
|
|
48
|
|
|
foreach ($hooks as $hook) { |
49
|
|
|
$hookableArgument = call_user_func($hook['callback'], $moduleId, $hookableArgument); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $hookableArgument; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function theHookIsForTheModule(array|string|null $filter, string $moduleId): bool |
56
|
|
|
{ |
57
|
|
|
if (null === $filter) { |
|
|
|
|
58
|
|
|
return true; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if (is_string($filter)) { |
|
|
|
|
62
|
|
|
return $filter === $moduleId; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return in_array($moduleId, $filter); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.