|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224 |
- <?php
-
-
- namespace yii\base;
-
-
- class Event extends Object
- {
-
-
- public $name;
-
-
- public $sender;
-
-
- public $handled = false;
-
-
- public $data;
-
-
-
- private static $_events = [];
-
-
-
-
- public static function on($class, $name, $handler, $data = null, $append = true)
- {
- $class = ltrim($class, '\\');
- if ($append || empty(self::$_events[$name][$class])) {
- self::$_events[$name][$class][] = [$handler, $data];
- } else {
- array_unshift(self::$_events[$name][$class], [$handler, $data]);
- }
- }
-
-
-
- public static function off($class, $name, $handler = null)
- {
- $class = ltrim($class, '\\');
- if (empty(self::$_events[$name][$class])) {
- return false;
- }
- if ($handler === null) {
- unset(self::$_events[$name][$class]);
- return true;
- } else {
- $removed = false;
- foreach (self::$_events[$name][$class] as $i => $event) {
- if ($event[0] === $handler) {
- unset(self::$_events[$name][$class][$i]);
- $removed = true;
- }
- }
- if ($removed) {
- self::$_events[$name][$class] = array_values(self::$_events[$name][$class]);
- }
-
- return $removed;
- }
- }
-
-
-
- public static function offAll()
- {
- self::$_events = [];
- }
-
-
-
- public static function hasHandlers($class, $name)
- {
- if (empty(self::$_events[$name])) {
- return false;
- }
- if (is_object($class)) {
- $class = get_class($class);
- } else {
- $class = ltrim($class, '\\');
- }
-
- $classes = array_merge(
- [$class],
- class_parents($class, true),
- class_implements($class, true)
- );
-
- foreach ($classes as $class) {
- if (!empty(self::$_events[$name][$class])) {
- return true;
- }
- }
-
- return false;
- }
-
-
-
- public static function trigger($class, $name, $event = null)
- {
- if (empty(self::$_events[$name])) {
- return;
- }
- if ($event === null) {
- $event = new static;
- }
- $event->handled = false;
- $event->name = $name;
-
- if (is_object($class)) {
- if ($event->sender === null) {
- $event->sender = $class;
- }
- $class = get_class($class);
- } else {
- $class = ltrim($class, '\\');
- }
-
- $classes = array_merge(
- [$class],
- class_parents($class, true),
- class_implements($class, true)
- );
-
- foreach ($classes as $class) {
- if (!empty(self::$_events[$name][$class])) {
- foreach (self::$_events[$name][$class] as $handler) {
- $event->data = $handler[1];
- call_user_func($handler[0], $event);
- if ($event->handled) {
- return;
- }
- }
- }
- }
- }
- }
|