| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImportWP; |
| 4 |
|
| 5 |
class EventHandler |
| 6 |
{ |
| 7 |
|
| 8 |
/** |
| 9 |
* List of stored events |
| 10 |
* |
| 11 |
* @var array $events |
| 12 |
*/ |
| 13 |
private $events; |
| 14 |
|
| 15 |
/** |
| 16 |
* Trigger event |
| 17 |
* |
| 18 |
* @param string $event |
| 19 |
* @param array $args |
| 20 |
* |
| 21 |
* @return mixed |
| 22 |
*/ |
| 23 |
public function run($event, $orignal_args = array()) |
| 24 |
{ |
| 25 |
$is_empty = false; |
| 26 |
if (empty($orignal_args)) { |
| 27 |
$is_empty = true; |
| 28 |
} else { |
| 29 |
$result = array_shift($orignal_args); |
| 30 |
} |
| 31 |
|
| 32 |
if (isset($this->events[$event]) && is_array($this->events[$event]) && !empty($this->events[$event])) { |
| 33 |
foreach ($this->events[$event] as $callback) { |
| 34 |
|
| 35 |
if (true === $is_empty) { |
| 36 |
$args = []; |
| 37 |
} else { |
| 38 |
$args = array_merge([$result], $orignal_args); |
| 39 |
} |
| 40 |
|
| 41 |
$result = call_user_func_array($callback, (array) $args); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
return $result; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Add event |
| 50 |
* |
| 51 |
* @param string $event |
| 52 |
* @param $callback |
| 53 |
*/ |
| 54 |
public function listen($event, $callback) |
| 55 |
{ |
| 56 |
|
| 57 |
if (!isset($this->events[$event])) { |
| 58 |
$this->events[$event] = array(); |
| 59 |
} |
| 60 |
|
| 61 |
$this->events[$event][] = $callback; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Remove event |
| 66 |
* |
| 67 |
* @param string $event |
| 68 |
* @param $callback |
| 69 |
*/ |
| 70 |
public function unlisten($event, $callback) |
| 71 |
{ |
| 72 |
if (isset($this->events[$event]) && in_array($callback, $this->events[$event], true)) { |
| 73 |
|
| 74 |
if (($key = array_search($callback, $this->events[$event])) !== false) { |
| 75 |
unset($this->events[$event][$key]); |
| 76 |
} |
| 77 |
|
| 78 |
if (empty($this->events[$event])) { |
| 79 |
unset($this->events[$event]); |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
|