1 <?php
2
3 namespace Docolight\Support\Traits;
4
5 use Closure;
6 use BadMethodCallException;
7
8 trait Macroable
9 {
10 11 12 13 14
15 protected static $macros = [];
16
17 18 19 20 21 22
23 public static function macro($name, callable $macro)
24 {
25 static::$macros[$name] = $macro;
26 }
27
28 29 30 31 32 33 34
35 public static function hasMacro($name)
36 {
37 return isset(static::$macros[$name]);
38 }
39
40 41 42 43 44 45 46 47 48 49
50 public static function __callStatic($method, $parameters)
51 {
52 if (static::hasMacro($method)) {
53 if (static::$macros[$method] instanceof Closure) {
54 return call_user_func_array(Closure::bind(static::$macros[$method], null, get_called_class()), $parameters);
55 } else {
56 return call_user_func_array(static::$macros[$method], $parameters);
57 }
58 }
59
60 throw new BadMethodCallException("Method {$method} does not exist.");
61 }
62
63 64 65 66 67 68 69 70 71 72
73 public function __call($method, $parameters)
74 {
75 if (static::hasMacro($method)) {
76 if (static::$macros[$method] instanceof Closure) {
77 return call_user_func_array(static::$macros[$method]->bindTo($this, get_class($this)), $parameters);
78 } else {
79 return call_user_func_array(static::$macros[$method], $parameters);
80 }
81 }
82
83 throw new BadMethodCallException("Method {$method} does not exist.");
84 }
85 }
86