-
Notifications
You must be signed in to change notification settings - Fork 0
/
CallableListener.php
108 lines (92 loc) · 2.31 KB
/
CallableListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
/**
* Qubus\EventDispatcher
*
* @link https://github.com/QubusPHP/event-dispatcher
* @copyright 2020 Joshua Parker <joshua@joshuaparker.dev>
* @copyright 2018 Filip Štamcar (original author Tor Morten Jensen)
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\EventDispatcher;
use Qubus\Exception\Data\TypeException;
use function call_user_func;
class CallableListener implements EventListener
{
/**
* The callable callback.
*
* @var callable $callable
*/
protected $callable;
/**
* Array of callable-listeners.
*
* @var array $listeners
*/
protected static array $listeners = [];
/**
* @param callable $callable
* @throws TypeException
*/
public function __construct($callable)
{
if (!is_callable($callable)) {
throw new TypeException('Parameter must be a callable.');
}
$this->callable = $callable;
static::$listeners[] = $this;
}
/**
* Gets callback.
*
* @return callable
*/
public function getCallable(): callable
{
return $this->callable;
}
/**
* {@inheritdoc}
*/
public function handle(Event $event): void
{
call_user_func($this->callable, $event);
}
/**
* Creates a callable-listener.
*
* @param callable $callable
* @throws TypeException
*/
public static function createFromCallable($callable): CallableListener
{
return new static($callable);
}
/**
* Finds the listener from the collection by its callable.
*
* @param callable $callable
* @return CallableListener|false
* @throws TypeException
*/
public static function findByCallable($callable): CallableListener|false
{
if (!is_callable($callable)) {
throw new TypeException('Parameter must be a callable.');
}
foreach (static::$listeners as $listener) {
if ($listener->getCallable() === $callable) {
return $listener;
}
}
return false;
}
/**
* Removes all registered callable-listeners.
*/
public static function clearListeners(): void
{
static::$listeners = [];
}
}