-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDispatcher.php
110 lines (96 loc) · 2.19 KB
/
Dispatcher.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
109
110
<?php
namespace Darya\Events;
/**
* Darya's event dispatcher implementation.
*
* @author Chris Andrew <[email protected]>
*/
class Dispatcher implements Dispatchable, Subscribable
{
/**
* Keys are event names and values are callables.
*
* @var array
*/
protected $listeners;
/**
* Ensure that a listeners array exists for the given event.
*
* @param string $event
*/
protected function touch($event)
{
if (!isset($this->listeners[$event])) {
$this->listeners[$event] = array();
}
}
/**
* Register a listener with the given event.
*
* @param string $event
* @param callable $callable
* @return void
*/
public function listen($event, $callable)
{
$this->touch($event);
$this->listeners[$event][] = $callable;
}
/**
* Unregister a listener from the given event.
*
* @param string $event
* @param callable $callable
*/
public function unlisten($event, $callable)
{
$this->touch($event);
$this->listeners[$event] = array_filter($this->listeners[$event], function ($value) use ($callable) {
return $value !== $callable;
});
}
/**
* Register the given subscriber's event listeners.
*
* @param Subscriber $subscriber
*/
public function subscribe(Subscriber $subscriber)
{
$subscriptions = $subscriber->getEventSubscriptions();
foreach ($subscriptions as $event => $listener) {
$this->listen($event, $listener);
}
}
/**
* Unregister the given subscriber's event listeners.
*
* @param Subscriber $subscriber
*/
public function unsubscribe(Subscriber $subscriber)
{
$subscriptions = $subscriber->getEventSubscriptions();
foreach ($subscriptions as $event => $listener) {
$this->unlisten($event, $listener);
}
}
/**
* Dispatch the given event.
*
* Optionally accepts arguments to pass to the event's registered listeners.
*
* @param string $event
* @param array $arguments [optional]
* @return array
*/
public function dispatch($event, array $arguments = array())
{
$this->touch($event);
$results = array();
foreach ((array) $this->listeners[$event] as $listener) {
if (is_callable($listener)) {
$results[] = call_user_func_array($listener, $arguments);
}
}
return $results;
}
}