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 |
||
7 | trait HasAuthorizations |
||
8 | { |
||
9 | /** |
||
10 | * Flag to check if user is authorized to use the button. |
||
11 | * |
||
12 | * @var bool |
||
13 | */ |
||
14 | protected $authorized = true; |
||
15 | |||
16 | /** |
||
17 | * Make a button if condition is true. |
||
18 | * |
||
19 | * @param bool|callable $condition |
||
20 | * @param string|array $options |
||
21 | * @return static |
||
22 | */ |
||
23 | public static function makeIf($condition, $options) |
||
31 | |||
32 | /** |
||
33 | * Make a button if the user is authorized. |
||
34 | * |
||
35 | * @param string $permission |
||
36 | * @param string|array $options |
||
37 | * @param Authorizable|null $user |
||
38 | * @return static |
||
39 | */ |
||
40 | View Code Duplication | public static function makeIfCan($permission, $options, Authorizable $user = null) |
|
52 | |||
53 | /** |
||
54 | * Make a button if the user is not authorized. |
||
55 | * |
||
56 | * @param string $permission |
||
57 | * @param string|array $options |
||
58 | * @param Authorizable|null $user |
||
59 | * @return static |
||
60 | */ |
||
61 | View Code Duplication | public static function makeIfCannot($permission, $options, Authorizable $user = null) |
|
73 | |||
74 | /** |
||
75 | * Set authorization status of the button. |
||
76 | * |
||
77 | * @param bool|callable $bool |
||
78 | * @return static |
||
79 | */ |
||
80 | public function authorized($bool) |
||
86 | |||
87 | /** |
||
88 | * Convert the Fluent instance to an array. |
||
89 | * |
||
90 | * @return array |
||
91 | */ |
||
92 | public function toArray() |
||
100 | } |
||
101 |
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.