-
Notifications
You must be signed in to change notification settings - Fork 5
/
Listener.php
84 lines (75 loc) · 2.07 KB
/
Listener.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
<?php
namespace yiicod\listener;
use Yii;
use yii\base\BootstrapInterface;
use yii\base\Component;
use yii\base\Event;
use yii\helpers\ArrayHelper;
/**
* Class Listener
*
* @package yiicod\listener\components
*/
class Listener extends Component implements BootstrapInterface
{
public $eventAliases = [
'@app/config/listeners.php',
];
/**
* @var array
*/
private static $_events;
public function init()
{
$events = [];
static::$_events = [];
foreach ($this->eventAliases as $alias) {
if (file_exists(Yii::getAlias($alias))) {
$events = ArrayHelper::merge($events, include(Yii::getAlias($alias)));
}
}
ksort($events);
foreach ($events as $priority => $keys) {
foreach ($keys as $event => $listeners) {
foreach ($listeners as $handler) {
list($class, $name) = explode('@', $event);
if (false === self::hasHandler($class, $name, $handler)) {
static::$_events[$class][$name][] = $handler;
Event::on($class, $name, $handler);
}
}
}
}
}
/**
* Register events
*
* @param \yii\base\Application $app
*/
public function bootstrap($app)
{
// Called in the init method
}
/**
* Check event list if handler exists for class.
*
* @param $class
* @param $name
* @param $handler
*
* @return bool
*/
public static function hasHandler(string $class, string $name, array $handler): bool
{
$result = array_filter((static::$_events[$class][$name] ?? []), function ($item) use ($handler) {
$item = array_map(function ($value) {
return trim($value, '\\');
}, $item);
$handler = array_map(function ($value) {
return trim($value, '\\');
}, $handler);
return $item === $handler;
});
return count($result) > 0;
}
}