<?php

namespace apexl\Io\includes;

use apexl\ClassEngine\EngineSingleton;

/**
 * Relatively crude hook system, will need to be improved
 * Class Hook
 * @package apexl\Io\includes
 */
class Hook extends EngineSingleton
{
    //an array of callables, keyed by name
    protected static $registeredCallbacks;
    protected static $disabled = false;

    public static function disable()
    {
        self::$disabled = true;
    }

    public static function enable()
    {
        self::$disabled = false;
    }

    public static function processHook($name)
    {
        $return = null;
        $args = func_get_args();
        //unset the name
        unset($args[0]);
        //second arg is always data, if its set.
        //@todo this will need to be made better
        if (!self::$disabled && isset(self::$registeredCallbacks[$name])) {
            foreach (self::$registeredCallbacks[$name] as $callback) {
                //@todo probably should be using callables, or add the option to at least
                //split into usable callback
                $return = call_user_func_array(explode(':', (string) $callback), $args);
                //reset the data arg with each hook return
                if (isset($return) && (isset($args[1]))) {
                    $args[1] = $return;
                }
            }
            //set return to the final altered data
            $return = $args[1];
        }
        //make sure we return anything passed as arg one, which is set in the foreach if altered. Otherwise, null.
        return $args[1] ?? $return;
    }

    /**
     * Function to register hook methods.
     * @param $name
     * @param $callback
     */
    public static function registerCallback($name, $callback)
    {
        self::$registeredCallbacks[$name][] = $callback;
    }
}
