1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Resque; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Resque event/plugin system class |
7
|
|
|
* |
8
|
|
|
* @package Resque/Event |
9
|
|
|
* @author Chris Boulton <[email protected]> |
10
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php |
11
|
|
|
*/ |
12
|
|
|
class Event |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var array Array containing all registered callbacks, indexked by event name. |
16
|
|
|
*/ |
17
|
|
|
private static $events = array(); |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Raise a given event with the supplied data. |
21
|
|
|
* |
22
|
|
|
* @param string $event Name of event to be raised. |
23
|
|
|
* @param mixed $data Optional, any data that should be passed to each callback. |
24
|
|
|
* @return true |
25
|
|
|
*/ |
26
|
|
|
public static function trigger($event, $data = null) |
27
|
|
|
{ |
28
|
|
|
if (!is_array($data)) { |
29
|
|
|
$data = array($data); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (empty(self::$events[$event])) { |
33
|
|
|
return true; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
foreach (self::$events[$event] as $callback) { |
37
|
|
|
if (!is_callable($callback)) { |
38
|
|
|
continue; |
39
|
|
|
} |
40
|
|
|
call_user_func_array($callback, $data); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return true; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Listen in on a given event to have a specified callback fired. |
48
|
|
|
* |
49
|
|
|
* @param string $event Name of event to listen on. |
50
|
|
|
* @param mixed $callback Any callback callable by call_user_func_array. |
51
|
|
|
* @return true |
52
|
|
|
*/ |
53
|
|
|
public static function listen($event, $callback) |
54
|
|
|
{ |
55
|
|
|
if (!isset(self::$events[$event])) { |
56
|
|
|
self::$events[$event] = array(); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
self::$events[$event][] = $callback; |
60
|
|
|
return true; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Stop a given callback from listening on a specific event. |
65
|
|
|
* |
66
|
|
|
* @param string $event Name of event. |
67
|
|
|
* @param mixed $callback The callback as defined when listen() was called. |
68
|
|
|
* @return true |
69
|
|
|
*/ |
70
|
|
|
public static function stopListening($event, $callback) |
71
|
|
|
{ |
72
|
|
|
if (!isset(self::$events[$event])) { |
73
|
|
|
return true; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$key = array_search($callback, self::$events[$event]); |
77
|
|
|
if ($key !== false) { |
78
|
|
|
unset(self::$events[$event][$key]); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return true; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* Call all registered listeners. |
86
|
|
|
*/ |
87
|
|
|
public static function clearListeners() |
88
|
|
|
{ |
89
|
|
|
self::$events = array(); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|