-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathEventEmitter.php
88 lines (59 loc) · 2.14 KB
/
EventEmitter.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
<?php
namespace Irc;
class EventEmitter {
protected $eventCallbacks = array();
protected $onceEventCallbacks = array();
public function on( $event, $callback ) {
if( strpos( $event, ',' ) !== false ) {
$events = explode( ',', $event );
foreach( $events as $event ) {
$this->on( trim( $event ), $callback );
}
return $this;
}
if( empty( $this->eventCallbacks[ $event ] ) )
$this->eventCallbacks[ $event ] = array();
$this->eventCallbacks[ $event ][] = $callback;
return $this;
}
public function off( $event, $callback ) {
if( empty( $this->eventCallbacks[ $event ] ) )
return $this;
$idx = null;
foreach( $this->eventCallbacks[ $event ] as $key => $cb )
if( $callback === $cb ) {
$idx = $key;
break;
}
array_splice( $this->eventCallbacks, $idx, 1 );
return $this;
}
public function once( $event, $callback ) {
if( empty( $this->onceEventCallbacks[ $event ] ) )
$this->onceEventCallbacks[ $event ] = array();
$this->onceEventCallbacks[ $event ][] = $callback;
return $this;
}
public function emit( $event, $args = array() ) {
if( strpos( $event, ',' ) !== false ) {
$events = explode( ',', $event );
foreach( $events as $event ) {
$this->emit( trim( $event ), $args );
}
return $this;
}
$args[ 'time' ] = time();
$args[ 'event' ] = $event;
$args[ 'sender' ] = $this;
if( !empty( $this->onceEventCallbacks[ $event ] ) ) {
foreach( $this->onceEventCallbacks[ $event ] as $callback )
call_user_func( $callback, (object)$args, $this );
$this->onceEventCallbacks[ $event ] = array();
}
if( !empty( $this->eventCallbacks[ $event ] ) ) {
foreach( $this->eventCallbacks[ $event ] as $callback )
call_user_func( $callback, (object)$args, $this );
}
return $this;
}
}