|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @author Marwan Al-Soltany <[email protected]> |
|
4
|
|
|
* @copyright Marwan Al-Soltany 2020 |
|
5
|
|
|
* For the full copyright and license information, please view |
|
6
|
|
|
* the LICENSE file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace MAKS\AmqpAgent\Helper; |
|
10
|
|
|
|
|
11
|
|
|
use Closure; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* A trait containing events handling functions (adds events triggering and binding capabilities) to a class. |
|
15
|
|
|
* @since 2.0.0 |
|
16
|
|
|
*/ |
|
17
|
|
|
trait EventTrait |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* Here lives all bindings. |
|
21
|
|
|
* @var array |
|
22
|
|
|
*/ |
|
23
|
|
|
protected static $events = []; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Executes callbacks attached to the passed event with the passed arguments. |
|
27
|
|
|
* @param string $event Event name. |
|
28
|
|
|
* @param array $arguments [optional] Arguments array. Note that the arguments will be spread (`...$args`) on the callback. |
|
29
|
|
|
* @return void |
|
30
|
|
|
*/ |
|
31
|
|
|
protected static function trigger(string $event, array $arguments = []): void |
|
32
|
|
|
{ |
|
33
|
|
|
if (isset(self::$events[$event]) && count(self::$events[$event])) { |
|
34
|
|
|
$callbacks = &self::$events[$event]; |
|
35
|
|
|
foreach ($callbacks as $callback) { |
|
36
|
|
|
call_user_func_array($callback, array_values($arguments)); |
|
37
|
|
|
} |
|
38
|
|
|
} else { |
|
39
|
|
|
self::$events[$event] = []; |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Binds the passed function to the passed event. |
|
45
|
|
|
* @param string $event Event name. |
|
46
|
|
|
* @param Closure $function A closure to process the event. |
|
47
|
|
|
* @return void |
|
48
|
|
|
*/ |
|
49
|
|
|
protected static function bind(string $event, Closure $function): void |
|
50
|
|
|
{ |
|
51
|
|
|
self::$events[$event][] = $function; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Returns array of all registered events as an array `['event.name' => [$cb1, $cb2, ...]]`. |
|
56
|
|
|
* @return array |
|
57
|
|
|
*/ |
|
58
|
|
|
public static function getEvents(): array |
|
59
|
|
|
{ |
|
60
|
|
|
return self::$events; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|