You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.6 KiB

<?php
declare(strict_types=1);
/*
* @author Robert Strutts
* @copyright (c) 2026, Robert Strutts
* @license MIT
*/
namespace IOcornerstone\Framework\Trait;
trait Macroable
{
protected static array $macros = [];
/**
* Register a custom macro.
*/
public static function macro(string $name, mixed $macro): void {
static::$macros[$name] = $macro;
}
/**
* Checks if macro is registered.
*/
public static function hasMacro(string $name): bool {
return isset(static::$macros[$name]);
}
/**
* Dynamically handle calls to the class.
*/
public function __call(string $method, mixed $parameters): mixed {
if (!static::hasMacro($method)) {
throw new \BadMethodCallException("Method {$method} does not exist.");
}
$macro = static::$macros[$method];
if ($macro instanceof \Closure) {
return call_user_func_array($macro->bindTo($this, static::class), $parameters);
}
return call_user_func_array($macro, $parameters);
}
/**
* Dynamically handle static calls to the class.
*/
public static function __callStatic(string $method, mixed $parameters): mixed {
if (!static::hasMacro($method)) {
throw new \BadMethodCallException("Method {$method} does not exist.");
}
$macro = static::$macros[$method];
if ($macro instanceof \Closure) {
return call_user_func_array(\Closure::bind($macro, null, static::class), $parameters);
}
return call_user_func_array($macro, $parameters);
}
}