1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Macroable; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use ReflectionClass; |
7
|
|
|
use ReflectionMethod; |
8
|
|
|
use BadMethodCallException; |
9
|
|
|
|
10
|
|
|
trait Macroable |
11
|
|
|
{ |
12
|
|
|
protected static $macros = []; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Register a custom macro. |
16
|
|
|
* |
17
|
|
|
* @param string $name |
18
|
|
|
* @param object|callable $macro |
19
|
|
|
*/ |
20
|
|
|
public static function macro(string $name, $macro) |
21
|
|
|
{ |
22
|
|
|
static::$macros[$name] = $macro; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Mix another object into the class. |
27
|
|
|
* |
28
|
|
|
* @param object $mixin |
29
|
|
|
*/ |
30
|
|
|
public static function mixin($mixin) |
31
|
|
|
{ |
32
|
|
|
$methods = (new ReflectionClass($mixin))->getMethods( |
33
|
|
|
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
foreach ($methods as $method) { |
37
|
|
|
$method->setAccessible(true); |
38
|
|
|
|
39
|
|
|
static::macro($method->name, $method->invoke($mixin)); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public static function hasMacro(string $name): bool |
44
|
|
|
{ |
45
|
|
|
return isset(static::$macros[$name]); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
View Code Duplication |
public static function __callStatic($method, $parameters) |
|
|
|
|
49
|
|
|
{ |
50
|
|
|
if (! static::hasMacro($method)) { |
51
|
|
|
throw new BadMethodCallException("Method {$method} does not exist."); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$macro = static::$macros[$method]; |
55
|
|
|
|
56
|
|
|
if ($macro instanceof Closure) { |
57
|
|
|
return call_user_func_array(Closure::bind($macro, null, static::class), $parameters); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return call_user_func_array($macro, $parameters); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
View Code Duplication |
public function __call($method, $parameters) |
|
|
|
|
64
|
|
|
{ |
65
|
|
|
if (! static::hasMacro($method)) { |
66
|
|
|
throw new BadMethodCallException("Method {$method} does not exist."); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$macro = static::$macros[$method]; |
70
|
|
|
|
71
|
|
|
if ($macro instanceof Closure) { |
72
|
|
|
return call_user_func_array($macro->bindTo($this, static::class), $parameters); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return call_user_func_array($macro, $parameters); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.