<?php

namespace Core;

class Hook
{
    protected static $actions = [];
    protected static $filters = [];

    public static function addAction($name, $callback, $priority = 10)
    {
        self::$actions[$name][$priority][] = $callback;
    }

    public static function doAction($name, ...$args)
    {
        if (!isset(self::$actions[$name])) return;
        ksort(self::$actions[$name]);
        foreach (self::$actions[$name] as $priority => $callbacks) {
            foreach ($callbacks as $callback) {
                call_user_func_array($callback, $args);
            }
        }
    }

    public static function addFilter($name, $callback, $priority = 10)
    {
        self::$filters[$name][$priority][] = $callback;
    }

    public static function applyFilters($name, $value, ...$args)
    {
        if (!isset(self::$filters[$name])) return $value;
        ksort(self::$filters[$name]);
        foreach (self::$filters[$name] as $priority => $callbacks) {
            foreach ($callbacks as $callback) {
                $value = call_user_func_array($callback, array_merge([$value], $args));
            }
        }
        return $value;
    }
}
