1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the slince/event-dispatcher package. |
5
|
|
|
* |
6
|
|
|
* (c) Slince <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Slince\EventDispatcher; |
13
|
|
|
|
14
|
|
|
class CallableListener implements ListenerInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* The callable callback. |
18
|
|
|
* |
19
|
|
|
* @var callable |
20
|
|
|
*/ |
21
|
|
|
protected $callable; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Array of callable-listeners. |
25
|
|
|
* |
26
|
|
|
* @var array |
27
|
|
|
*/ |
28
|
|
|
protected static $listeners = []; |
29
|
|
|
|
30
|
|
|
public function __construct($callable) |
31
|
|
|
{ |
32
|
|
|
$this->callable = $callable; |
33
|
|
|
static::$listeners[] = $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Gets callback. |
38
|
|
|
* |
39
|
|
|
* @return callable |
40
|
|
|
*/ |
41
|
|
|
public function getCallable() |
42
|
|
|
{ |
43
|
|
|
return $this->callable; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritdoc} |
48
|
|
|
*/ |
49
|
|
|
public function handle(Event $event) |
50
|
|
|
{ |
51
|
|
|
call_user_func($this->callable, $event); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Creates a callable-listener. |
56
|
|
|
* |
57
|
|
|
* @param callable $callable |
58
|
|
|
* |
59
|
|
|
* @return CallableListener |
60
|
|
|
*/ |
61
|
|
|
public static function createFromCallable($callable) |
62
|
|
|
{ |
63
|
|
|
$listener = new static($callable); |
64
|
|
|
|
65
|
|
|
return $listener; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Finds the listener from the collection by its callable. |
70
|
|
|
* |
71
|
|
|
* @param callable $callable |
72
|
|
|
* |
73
|
|
|
* @return CallableListener|false |
74
|
|
|
*/ |
75
|
|
|
public static function findByCallable($callable) |
76
|
|
|
{ |
77
|
|
|
foreach (static::$listeners as $listener) { |
78
|
|
|
if ($listener->getCallable() == $callable) { |
79
|
|
|
return $listener; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
return false; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Removes all registered callable-listeners. |
88
|
|
|
*/ |
89
|
|
|
public static function clearListeners() |
90
|
|
|
{ |
91
|
|
|
static::$listeners = []; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|