| 1 |
<?php namespace WpFluent; |
| 2 |
|
| 3 |
use WpFluent\QueryBuilder\QueryBuilderHandler; |
| 4 |
use WpFluent\QueryBuilder\Raw; |
| 5 |
|
| 6 |
class EventHandler |
| 7 |
{ |
| 8 |
/** |
| 9 |
* @var array |
| 10 |
*/ |
| 11 |
protected $events = array(); |
| 12 |
|
| 13 |
/** |
| 14 |
* @var array |
| 15 |
*/ |
| 16 |
protected $firedEvents = array(); |
| 17 |
|
| 18 |
/** |
| 19 |
* @return array |
| 20 |
*/ |
| 21 |
public function getEvents() |
| 22 |
{ |
| 23 |
return $this->events; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* @param $event |
| 28 |
* @param $table |
| 29 |
* |
| 30 |
* @return callable|null |
| 31 |
*/ |
| 32 |
public function getEvent($event, $table = ':any') |
| 33 |
{ |
| 34 |
if ($table instanceof Raw) { |
| 35 |
return null; |
| 36 |
} |
| 37 |
return isset($this->events[$table][$event]) ? $this->events[$table][$event] : null; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* @param $event |
| 42 |
* @param string $table |
| 43 |
* @param callable $action |
| 44 |
* |
| 45 |
* @return void |
| 46 |
*/ |
| 47 |
public function registerEvent($event, $table, \Closure $action) |
| 48 |
{ |
| 49 |
$table = $table ?: ':any'; |
| 50 |
|
| 51 |
$this->events[$table][$event] = $action; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* @param $event |
| 56 |
* @param string $table |
| 57 |
* |
| 58 |
* @return void |
| 59 |
*/ |
| 60 |
public function removeEvent($event, $table = ':any') |
| 61 |
{ |
| 62 |
unset($this->events[$table][$event]); |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* @param QueryBuilderHandler $queryBuilder |
| 67 |
* @param $event |
| 68 |
* @return mixed |
| 69 |
*/ |
| 70 |
public function fireEvents($queryBuilder, $event) |
| 71 |
{ |
| 72 |
$statements = $queryBuilder->getStatements(); |
| 73 |
$tables = isset($statements['tables']) ? $statements['tables'] : array(); |
| 74 |
|
| 75 |
// Events added with :any will be fired in case of any table, |
| 76 |
// we are adding :any as a fake table at the beginning. |
| 77 |
array_unshift($tables, ':any'); |
| 78 |
|
| 79 |
// Fire all events |
| 80 |
foreach ($tables as $table) { |
| 81 |
// Fire before events for :any table |
| 82 |
if ($action = $this->getEvent($event, $table)) { |
| 83 |
// Make an event id, with event type and table |
| 84 |
$eventId = $event . $table; |
| 85 |
|
| 86 |
// Fire event |
| 87 |
$handlerParams = func_get_args(); |
| 88 |
unset($handlerParams[1]); // we do not need $event |
| 89 |
// Add to fired list |
| 90 |
$this->firedEvents[] = $eventId; |
| 91 |
$result = call_user_func_array($action, $handlerParams); |
| 92 |
if (!is_null($result)) { |
| 93 |
return $result; |
| 94 |
}; |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
} |
| 99 |
|