Macroable.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Trait allowing runtime registration of custom static and instance methods via macro. |
| 5 | * Stores callables in a static map and dispatches unknown methods to them. |
| 6 | * Used by Application, Filesystem, and HTTP Request for extensibility. |
| 7 | * |
| 8 | * @package Framework |
| 9 | * @subpackage Supports\Traits |
| 10 | * @since 1.0.0 |
| 11 | */ |
| 12 | namespace Kirki\Framework\Supports\Traits; |
| 13 | |
| 14 | \defined('ABSPATH') || exit; |
| 15 | use BadMethodCallException; |
| 16 | trait Macroable |
| 17 | { |
| 18 | /** |
| 19 | * The macros. |
| 20 | * |
| 21 | * @var array |
| 22 | * |
| 23 | * @since 1.0.0 |
| 24 | */ |
| 25 | protected static array $macros = []; |
| 26 | /** |
| 27 | * Register a macro. |
| 28 | * |
| 29 | * @param mixed $name The name. |
| 30 | * @param callable $macro The macro. |
| 31 | * |
| 32 | * @return void |
| 33 | * |
| 34 | * @since 1.0.0 |
| 35 | */ |
| 36 | public static function macro($name, callable $macro) |
| 37 | { |
| 38 | static::$macros[$name] = $macro; |
| 39 | } |
| 40 | /** |
| 41 | * Check if a macro is registered. |
| 42 | * |
| 43 | * @param mixed $name The name. |
| 44 | * |
| 45 | * @return bool |
| 46 | * |
| 47 | * @since 1.0.0 |
| 48 | */ |
| 49 | public static function has_macro($name) |
| 50 | { |
| 51 | return isset(static::$macros[$name]); |
| 52 | } |
| 53 | /** |
| 54 | * Dynamically handle calls to the class. |
| 55 | * |
| 56 | * @param string $method The method name. |
| 57 | * @param array $arguments The method arguments. |
| 58 | * |
| 59 | * @return mixed |
| 60 | * |
| 61 | * @throws \BadMethodCallException |
| 62 | * |
| 63 | * @since 1.0.0 |
| 64 | */ |
| 65 | public function __call(string $method, array $arguments) |
| 66 | { |
| 67 | if (isset(static::$macros[$method])) { |
| 68 | return \call_user_func_array(static::$macros[$method]->bindTo($this, static::class), $arguments); |
| 69 | } |
| 70 | throw new BadMethodCallException(\sprintf('Method %s::%s does not exist.', static::class, esc_html($method))); |
| 71 | } |
| 72 | /** |
| 73 | * Dynamically handle calls to the class. |
| 74 | * |
| 75 | * @param string $method The method name. |
| 76 | * @param array $arguments The method arguments. |
| 77 | * |
| 78 | * @return mixed |
| 79 | * |
| 80 | * @throws \BadMethodCallException |
| 81 | * |
| 82 | * @since 1.0.0 |
| 83 | */ |
| 84 | public static function __callStatic(string $method, array $arguments) |
| 85 | { |
| 86 | if (isset(static::$macros[$method])) { |
| 87 | return \call_user_func_array(static::$macros[$method]->bindTo(null, static::class), $arguments); |
| 88 | } |
| 89 | throw new BadMethodCallException(\sprintf('Method %s::%s does not exist.', static::class, esc_html($method))); |
| 90 | } |
| 91 | } |
| 92 |