| 1 |
<?php |
| 2 |
|
| 3 |
namespace Illuminate\Support\Traits; |
| 4 |
|
| 5 |
use BadMethodCallException; |
| 6 |
use Closure; |
| 7 |
use ReflectionClass; |
| 8 |
use ReflectionMethod; |
| 9 |
use RuntimeException; |
| 10 |
use Throwable; |
| 11 |
|
| 12 |
trait Macroable |
| 13 |
{ |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
protected static $macros = []; |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
public static function macro($name, $macro) |
| 32 |
{ |
| 33 |
static::$macros[$name] = $macro; |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
public static function mixin($mixin, $replace = true) |
| 46 |
{ |
| 47 |
$methods = (new ReflectionClass($mixin))->getMethods( |
| 48 |
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED |
| 49 |
); |
| 50 |
|
| 51 |
foreach ($methods as $method) { |
| 52 |
if ($replace || ! static::hasMacro($method->name)) { |
| 53 |
static::macro($method->name, $method->invoke($mixin)); |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public static function hasMacro($name) |
| 65 |
{ |
| 66 |
return isset(static::$macros[$name]); |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
public static function flushMacros() |
| 75 |
{ |
| 76 |
static::$macros = []; |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
public static function __callStatic($method, $parameters) |
| 89 |
{ |
| 90 |
if (! static::hasMacro($method)) { |
| 91 |
throw new BadMethodCallException(sprintf( |
| 92 |
'Method %s::%s does not exist.', static::class, $method |
| 93 |
)); |
| 94 |
} |
| 95 |
|
| 96 |
$macro = static::$macros[$method]; |
| 97 |
|
| 98 |
if ($macro instanceof Closure) { |
| 99 |
$macro = $macro->bindTo(null, static::class); |
| 100 |
} |
| 101 |
|
| 102 |
return $macro(...$parameters); |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
public function __call($method, $parameters) |
| 115 |
{ |
| 116 |
if (! static::hasMacro($method)) { |
| 117 |
throw new BadMethodCallException(sprintf( |
| 118 |
'Method %s::%s does not exist.', static::class, $method |
| 119 |
)); |
| 120 |
} |
| 121 |
|
| 122 |
$macro = static::$macros[$method]; |
| 123 |
|
| 124 |
if ($macro instanceof Closure) { |
| 125 |
try { |
| 126 |
$macro = $macro->bindTo($this, static::class) ?? throw new RuntimeException; |
| 127 |
} catch (Throwable) { |
| 128 |
$macro = $macro->bindTo(null, static::class); |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
return $macro(...$parameters); |
| 133 |
} |
| 134 |
} |