1
|
|
|
<?php |
2
|
|
|
namespace Ubiquity\events; |
3
|
|
|
|
4
|
|
|
use Ubiquity\cache\CacheManager; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Manage events |
8
|
|
|
* |
9
|
|
|
* @author jc |
10
|
|
|
* |
11
|
|
|
*/ |
12
|
|
|
class EventsManager { |
13
|
|
|
|
14
|
|
|
private static string $key = 'events/events'; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* |
18
|
|
|
* @var array|mixed |
19
|
|
|
*/ |
20
|
|
|
protected static $managedEvents = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Starts the event manager (in app/config/services.php) |
24
|
|
|
*/ |
25
|
3 |
|
public static function start():void { |
26
|
3 |
|
if (CacheManager::$cache->exists(self::$key)) { |
27
|
|
|
self::$managedEvents = CacheManager::$cache->fetch(self::$key); |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Adds a listener on eventName |
33
|
|
|
* @param string $eventName |
34
|
|
|
* @param EventListenerInterface|callable $action |
35
|
|
|
*/ |
36
|
8 |
|
public static function addListener(string $eventName, $action):void { |
37
|
8 |
|
if (! isset(self::$managedEvents[$eventName])) { |
38
|
2 |
|
self::$managedEvents[$eventName] = []; |
39
|
|
|
} |
40
|
8 |
|
self::$managedEvents[$eventName][] = $action; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Store the managed events in cache (do not use in prod) |
45
|
|
|
*/ |
46
|
1 |
|
public static function store():void { |
47
|
1 |
|
CacheManager::$cache->store(self::$key, self::$managedEvents); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Trigger an event |
52
|
|
|
* @param string $eventName |
53
|
|
|
* @param mixed ...$params |
54
|
|
|
*/ |
55
|
157 |
|
public static function trigger(string $eventName, &...$params):void { |
56
|
157 |
|
if (isset(self::$managedEvents[$eventName])) { |
57
|
18 |
|
foreach (self::$managedEvents[$eventName] as $action) { |
58
|
18 |
|
self::triggerOne($action, $params); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
18 |
|
private static function triggerOne($action, &$params):void { |
64
|
18 |
|
if (\is_callable($action)) { |
65
|
|
|
\call_user_func_array($action, $params); |
66
|
18 |
|
} elseif (is_subclass_of($action, EventListenerInterface::class)) { |
67
|
18 |
|
\call_user_func_array([ |
68
|
18 |
|
new $action(), |
69
|
18 |
|
'on' |
70
|
18 |
|
], $params); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
|