<?php
namespace Lia\Addon;
/**
* @todo add a wildcard hook that triggers on all hooks - would be great for debugging & showing a list of all hooks
*/
class Hook extends \Lia\Addon {
public string $fqn = 'lia:server.hook';
/**
* array of hooks like `['hook.name'=>[ [$object, 'method'], function(){echo "one";} ] ];`
*/
public $hooks = [];
public function init_lia(){
$lia = $this->lia;
$lia->methods['hook'] = [$this, 'add'];
$lia->methods['call_hook'] = [$this, 'call'];
$lia->methods['ready'] = function()use ($lia){$this->call('LiaReady', $lia);};
// @NOTE Hook addon has an 'on' prefix ... I think I might discontinue this feature
$lia->prefixes['on'] = [$this, 'prefix_method_added'];
}
/**
* Add an object's method as a hook.
* @param object $obj an object
* @param string $method a method name on the object
* @param $hook_name the hook name to use
*
* @usage declare onSome_Hook to add that method for hook named `some.hook`
*/
public function prefix_method_added($obj, $method, $hook_name){
// var_dump("Add hook $hook_name");
// var_dump($method);
// exit;
$this->add($hook_name, [$obj, $method]);
}
/**
*
* @param $name name of the hook
* @param $callable a callable
*/
public function add($name, $callable){
$name = strtolower($name);
$this->hooks[$name][] = $callable;
}
/**
*
* @return array of return values of each hook called.
*/
public function call($name, ...$args){
$name = strtolower($name);
$ret = [];
foreach ($this->hooks[$name]??[] as $h){
$ret[] = $h(...$args);
}
return $ret;
}
// public function scheduleFromPrefix($eventName, $callable){
// if (substr($eventName,0,1)=='_')$eventName = substr($eventName,1);
// $this->lia->api('lia:event.schedule', $eventName, $callable);
// }
}