|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ubiquity\events; |
|
4
|
|
|
|
|
5
|
|
|
use Ubiquity\cache\CacheManager; |
|
6
|
|
|
use Ubiquity\utils\base\UArray; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Manage events |
|
10
|
|
|
* |
|
11
|
|
|
* @author jc |
|
12
|
|
|
* |
|
13
|
|
|
*/ |
|
14
|
|
|
class EventsManager { |
|
15
|
|
|
private static $key = "events/events"; |
|
16
|
|
|
/** |
|
17
|
|
|
* |
|
18
|
|
|
* @var array|mixed |
|
19
|
|
|
*/ |
|
20
|
|
|
protected static $managedEvents = [ ]; |
|
21
|
|
|
|
|
22
|
1 |
|
public static function start() { |
|
23
|
1 |
|
if (CacheManager::$cache->exists ( self::$key )) { |
|
24
|
|
|
self::$managedEvents = CacheManager::$cache->fetch ( self::$key ); |
|
25
|
|
|
} |
|
26
|
1 |
|
} |
|
27
|
|
|
|
|
28
|
1 |
|
public static function addListener($eventName, $action) { |
|
29
|
1 |
|
if (! isset ( self::$managedEvents [$eventName] )) { |
|
30
|
1 |
|
self::$managedEvents [$eventName] = [ ]; |
|
31
|
|
|
} |
|
32
|
1 |
|
self::$managedEvents [$eventName] [] = $action; |
|
33
|
1 |
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
public static function store() { |
|
36
|
1 |
|
CacheManager::$cache->store ( self::$key, "return " . UArray::asPhpArray ( self::$managedEvents, 'array' ) . ';' ); |
|
37
|
1 |
|
} |
|
38
|
|
|
|
|
39
|
77 |
|
public static function trigger($eventName, &...$params) { |
|
40
|
77 |
|
if (isset ( self::$managedEvents [$eventName] )) { |
|
41
|
2 |
|
foreach ( self::$managedEvents [$eventName] as $action ) { |
|
42
|
2 |
|
self::triggerOne ( $action, $params ); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
77 |
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
private static function triggerOne($action, &$params) { |
|
48
|
2 |
|
if (\is_callable ( $action )) { |
|
49
|
|
|
\call_user_func_array ( $action, $params ); |
|
50
|
2 |
|
} elseif (is_subclass_of ( $action, EventListenerInterface::class )) { |
|
51
|
2 |
|
\call_user_func_array ( [ new $action (),"on" ], $params ); |
|
52
|
|
|
} |
|
53
|
2 |
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
|