Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 10 | trait Macroable |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * The registered string macros. |
||
| 14 | * |
||
| 15 | * @var array |
||
| 16 | */ |
||
| 17 | protected static $macros = []; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Register a custom macro. |
||
| 21 | * |
||
| 22 | * @param string $name |
||
| 23 | * @param object|callable $macro |
||
| 24 | * |
||
| 25 | * @return void |
||
| 26 | 9 | */ |
|
| 27 | public static function macro($name, $macro) |
||
| 28 | 9 | { |
|
| 29 | 9 | static::$macros[$name] = $macro; |
|
| 30 | } |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Mix another object into the class. |
||
| 34 | * |
||
| 35 | * @param object $mixin |
||
| 36 | * @param bool $replace |
||
| 37 | * @return void |
||
| 38 | * |
||
| 39 | * @throws \ReflectionException |
||
| 40 | 2 | */ |
|
| 41 | public static function mixin($mixin, $replace = true) |
||
| 42 | 2 | { |
|
| 43 | 2 | $methods = (new ReflectionClass($mixin))->getMethods( |
|
| 44 | ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED |
||
| 45 | ); |
||
| 46 | 2 | ||
| 47 | 2 | foreach ($methods as $method) { |
|
| 48 | 2 | if ($replace || ! static::hasMacro($method->name)) { |
|
| 49 | 2 | $method->setAccessible(true); |
|
| 50 | static::macro($method->name, $method->invoke($mixin)); |
||
|
|
|||
| 51 | } |
||
| 52 | 2 | } |
|
| 53 | } |
||
| 54 | |||
| 55 | /** |
||
| 56 | * Checks if macro is registered. |
||
| 57 | * |
||
| 58 | * @param string $name |
||
| 59 | * @return bool |
||
| 60 | 9 | */ |
|
| 61 | public static function hasMacro($name) |
||
| 62 | 9 | { |
|
| 63 | return isset(static::$macros[$name]); |
||
| 64 | } |
||
| 65 | |||
| 66 | /** |
||
| 67 | * Dynamically handle calls to the class. |
||
| 68 | * |
||
| 69 | * @param string $method |
||
| 70 | * @param array $parameters |
||
| 71 | * @return mixed |
||
| 72 | * |
||
| 73 | * @throws \BadMethodCallException |
||
| 74 | 2 | */ |
|
| 75 | View Code Duplication | public static function __callStatic($method, $parameters) |
|
| 91 | |||
| 92 | /** |
||
| 93 | * Dynamically handle calls to the class. |
||
| 94 | * |
||
| 95 | * @param string $method |
||
| 96 | * @param array $parameters |
||
| 97 | * @return mixed |
||
| 98 | * |
||
| 99 | * @throws \BadMethodCallException |
||
| 100 | 8 | */ |
|
| 101 | View Code Duplication | public function __call($method, $parameters) |
|
| 117 | } |
||
| 118 |
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: