parent
535c14668d
commit
922e13d022
@ -1,6 +1,10 @@ |
||||
<?php |
||||
namespace ex; |
||||
|
||||
use libs\Traits\Macroable; |
||||
|
||||
class Example2 { |
||||
use Macroable; |
||||
public int $version = 22; |
||||
public function hi(): void { echo "Hi! \n"; } |
||||
} |
||||
|
||||
@ -0,0 +1,60 @@ |
||||
<?php |
||||
|
||||
namespace libs\Traits; |
||||
|
||||
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); |
||||
} |
||||
} |
||||
Loading…
Reference in new issue