Debian Codegraph @

lib/3rdParty/composer/illuminate/macroable/Traits/Macroable.php

raw symbols SCIP
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 * The registered string macros.
16 *
17 * @var array
18 */
19 protected static $macros = [];
20
21 /**
22 * Register a custom macro.
23 *
24 * @param string $name
25 * @param object|callable $macro
26 *
27 * @param-closure-this static $macro
28 *
29 * @return void
30 */
31 public static function macro($name, $macro)
32 {
33 static::$macros[$name] = $macro;
34 }
35
36 /**
37 * Mix another object into the class.
38 *
39 * @param object $mixin
40 * @param bool $replace
41 * @return void
42 *
43 * @throws \ReflectionException
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 * Checks if macro is registered.
60 *
61 * @param string $name
62 * @return bool
63 */
64 public static function hasMacro($name)
65 {
66 return isset(static::$macros[$name]);
67 }
68
69 /**
70 * Flush the existing macros.
71 *
72 * @return void
73 */
74 public static function flushMacros()
75 {
76 static::$macros = [];
77 }
78
79 /**
80 * Dynamically handle calls to the class.
81 *
82 * @param string $method
83 * @param array $parameters
84 * @return mixed
85 *
86 * @throws \BadMethodCallException
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 * Dynamically handle calls to the class.
107 *
108 * @param string $method
109 * @param array $parameters
110 * @return mixed
111 *
112 * @throws \BadMethodCallException
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 }