-
Notifications
You must be signed in to change notification settings - Fork 36
/
EventCore.php
407 lines (345 loc) · 10.7 KB
/
EventCore.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php
App::uses('AppEvents', 'Events.Lib');
EventCore::getInstance();
class EventCore {
/**
* Event objects
*
* @var array
*/
protected $_eventClasses = array();
/**
* Available handlers and what eventClasses they appear in.
*
* @var array
*/
protected $_eventHandlerCache = array();
/**
* a cache of the event names
*
* @var object
* @access public
*/
public $eventNameCache;
/**
* a cache of the handler names
*
* @var object
* @access public
*/
public $handlerNameCache;
/**
* a cache of the plugin names
*
* @var object
* @access public
*/
public $pluginNameCache;
private $__availablePlugins = array();
private $__installedPlugins = array();
private $__pluginsMap = array(
'testEvent' => 'all',
'setupRoutes' => 'all',
'setupExtensions' => 'all'
);
private function __construct() {}
private function __clone() {}
/**
* Returns a singleton instance of the EventCore class.
*
* @return EventCore instance
* @access public
*/
public function getInstance() {
static $instance = array();
if (empty($instance)) {
$instance[0] = new EventCore();
$instance[0]->_loadEventHandlers();
}
return $instance[0];
}
/**
* Trigger an event or array of events
*
* @param string|array $eventName
* @param array $data (optional) Array of data to pass along to the event handler
* @return array
*
*/
static public function trigger(&$HandlerObject, $eventName, $data = array()) {
$_this = EventCore::getInstance();
if(!is_array($eventName)) {
$eventName = array($eventName);
}
$eventNames = Set::filter($eventName);
$return = array();
foreach($eventNames as $eventName) {
$eventData = EventCore::_parseEventName($eventName);
$return[$eventData['event']] = EventCore::_dispatchEvent($HandlerObject, $eventData['scope'], $eventData['event'], $data);
}
return $return;
}
/**
* @brief Get a list of plugins that will be affected by running an event
*
* This will return all plugins that have an event class but sometimes if
* you need to run a global trigger but want to do it one at a time this
* list will help out.
*
* @param string $eventName the name of the event to run
* @access public
*
* @return array the array of plugins that will be run
*/
public function pluginsWith($eventName) {
$_this = EventCore::getInstance();
if(!isset($_this->_eventHandlerCache[$eventName])) {
return array();
}
$return = array();
foreach($_this->_eventHandlerCache[$eventName] as $plugin) {
$return[] = $_this->_extractPluginName($plugin);
}
return $return;
}
/**
* @brief dynamically turn plugins on during a request.
*
* This can be used to turn a plugin on programatically.
*
* @param mixed $plugins single / list of plugins to turn on
* @param bool $allowUninstalled allow turning on a plugin that is not installed (not recommended)
*
* @return bool true if they were added, false if not
*/
static public function activatePlugins($plugins = array(), $allowUninstalled = false) {
$_this = EventCore::getInstance();
if(!is_array($plugins)) {
$plugins = array($plugins);
}
if(empty($plugins)) {
return false;
}
if($allowUninstalled) {
$_this->__installedPlugins = App::objects('plugin');
}
else {
$_this->__installedPlugins = CakePlugin::loaded();
}
foreach($plugins as $plugin) {
if(in_array($plugin, $_this->__installedPlugins) && !in_array($plugin, $_this->__availablePlugins)) {
$_this->__availablePlugins[] = $plugin;
}
}
return true;
}
/**
* @brief check if a plugin is active for the current request
*
* This method is used within the core to stop people accessing the controllers
* and actions directly. It can also be used to see if plugins are active
* for the request. Even if something is installed and active, it may have
* been dynamically turned off (or the other way round)
*
* @access public
*
* @param string $plugin the name of the plugin to check
*
* @return bool true if its active, false if not
*/
public function isPluginActive($plugin) {
$_this = EventCore::getInstance();
if(!$plugin || !in_array(Inflector::camelize($plugin), $_this->__availablePlugins)) {
return false;
}
return true;
}
/**
* Loads all available event handler classes for enabled plugins
*
*/
protected function _loadEventHandlers() {
$this->_eventHandlerCache = Cache::read('event_handlers', 'core');
if(!empty($this->_eventHandlerCache)) {
return;
}
$plugins = CakePlugin::loaded();
foreach((array)$plugins as $pluginName) {
self::loadEventHandler($pluginName);
}
Cache::write('event_handlers', $this->_eventHandlerCache, 'core');
}
public static function loadEventHandler($plugin) {
$_this = self::getInstance();
$filename = App::pluginPath($plugin) . 'Lib' . DS . $plugin . 'Events.php';
$className = $plugin . 'Events';
if(file_exists($filename)) {
if(EventCore::_loadEventClass($className, $filename)) {
EventCore::_getAvailableHandlers($_this->_eventClasses[$className]);
}
}
}
/**
* Dispatch Event
*
* @param string $eventName
* @param array $data (optional)
* @return array
*
*/
static protected function _dispatchEvent(&$HandlerObject, $scope, $eventName, $data = array()) {
$_this = EventCore::getInstance();
$eventHandlerMethod = $_this->_handlerMethodName($eventName);
$return = array();
if(isset($_this->_eventHandlerCache[$eventName])) {
foreach($_this->_eventHandlerCache[$eventName] as $eventClass) {
$pluginName = EventCore::_extractPluginName($eventClass);
$pluginType = 'loaded';
if(isset($_this->__pluginsMap[$eventName])) {
$pluginType = $_this->__pluginsMap[$eventName];
}
if(!in_array(Inflector::camelize($pluginName), (array)InfinitasPlugin::listPlugins($pluginType))) {
continue;
}
if(($scope == 'Global' || $scope == $pluginName)) {
EventCore::_loadEventClass($eventClass);
$Event = new Event($eventName, $HandlerObject, $pluginName);
$return[$pluginName] = call_user_func_array(array($_this->_eventClasses[$eventClass], $eventHandlerMethod), array($Event, $data));
}
}
}
return $return;
}
/**
* takes the event name and breaks it down into the different parts setting
* some defaults for gloabl events. results are cached to avoid importing
* and alling the string class to much.
*
* @param string $eventName the name of the event
* @return array the scope + event name
*/
protected function _parseEventName($eventName) {
$_this = EventCore::getInstance();
if(!isset($_this->eventNameCache->{$eventName})) {
$eventTokens = String::tokenize($eventName, '.');
$scope = 'Global';
$event = $eventTokens[0];
if (count($eventTokens) > 1) {
list($scope, $event) = $eventTokens;
if($scope != Inflector::camelize($scope)) {
user_error(sprintf('%s.%s is not valid, camelized plugins required', $scope, $event));
$scope = Inflector::camelize($scope, E_USER_NOTICE);
}
}
$_this->eventNameCache->{$eventName} = array(
'scope' => $scope,
'event' => $event
);
}
return $_this->eventNameCache->{$eventName};
}
/**
* Converts event name into a handler method name and caches the result
* so that there are less calls to the inflector method.
*
* @param string $eventName
* @return string the method to be called
*
*/
protected function _handlerMethodName($eventName) {
$_this = EventCore::getInstance();
if(!isset($_this->handlerNameCache->{$eventName})) {
$_this->handlerNameCache->{$eventName} = 'on' . Inflector::camelize($eventName);
}
return $_this->handlerNameCache->{$eventName};
}
/**
* Loads list of available event handlers in a event object
*
* @param object $Event
* @access private
*/
protected function _getAvailableHandlers($Event) {
if(is_object($Event)) {
$_this = EventCore::getInstance();
$reflection = new ReflectionClass($Event);
$classMethods = array_filter($reflection->getMethods(), create_function('$v', 'return $v->class == "'.get_class($Event).'" && substr($v->name, 0, 2) == "on";'));
$handlers = array_map(create_function('$v', 'return lcfirst(substr($v->name, 2));'), $classMethods);
foreach($handlers as $handlerName) {
$_this->_eventHandlerCache[$handlerName][] = get_class($Event);
}
}
}
/**
* Loads and initialises an event class
*
* @param string $className the event class to load
* @param string $filename the file name of the event
* @access private
*/
protected function _loadEventClass($className, $filename = false) {
$_this = EventCore::getInstance();
if(isset($_this->_eventClasses[$className]) && is_object($_this->_eventClasses[$className])) {
return true;
}
if($filename === false) {
$baseName = Inflector::underscore($className) . '.php';
$pluginName = Inflector::camelize(preg_replace('/events.php$/i', '', $baseName));
$pluginPath = App::pluginPath($pluginName);
$filename = $pluginPath . $baseName;
}
if(empty($pluginName)) {
$baseName = Inflector::underscore($className) . '.php';
$pluginName = Inflector::camelize(preg_replace('/events.php$/i', '', $baseName));
}
require $filename;
try{
$_this->_eventClasses[$className] = new $className();
return true;
}
catch(Exception $e) {
$this->log(serialize($e), 'core');
return false;
}
}
/**
* Extracts the plugin name out of the class name and caches the value
* so that the strtolower and other stuff does not need to be called
* so many times.
*
* @param string $className the name of the class being called
* @return string the plugin being called.
* @access private
*/
protected function _extractPluginName($className) {
$_this = EventCore::getInstance();
if(!isset($_this->pluginNameCache->{$className})) {
$_this->pluginNameCache->{$className} = substr($className, 0, strlen($className) - 6);
}
return $_this->pluginNameCache->{$className};
}
}
/**
* Event Object
*/
class Event {
/**
* Contains assigned values
*
* @var array
*
protected $values = array();*/
/**
* Constructor with EventName and EventData (optional)
*
* Event Data is automaticly assigned as properties by array key
*
* @param string $eventName Name of the Event
* @param array $data optional array with k/v data
*/
public function __construct($eventName, $HandlerObject, $pluginName) {
$this->name = $eventName;
$this->Handler = $HandlerObject;
$this->plugin = $pluginName;
}
}