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 |
||
| 29 | trait ByGroup |
||
| 30 | { |
||
| 31 | /** |
||
| 32 | * Get the authenticated user |
||
| 33 | * |
||
| 34 | * @return User |
||
| 35 | */ |
||
| 36 | abstract public function user(); |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Get the groups and the groups it supersedes. |
||
| 40 | * |
||
| 41 | * @return array |
||
| 42 | */ |
||
| 43 | abstract protected function getGroupStructure(); |
||
| 44 | |||
| 45 | |||
| 46 | /** |
||
| 47 | * Get group and all groups it supersedes (recursively). |
||
| 48 | * |
||
| 49 | * @param string|array $group Single group or array of groups |
||
| 50 | * @return array |
||
| 51 | */ |
||
| 52 | 5 | protected function expandGroup($group) |
|
| 70 | |||
| 71 | |||
| 72 | /** |
||
| 73 | * Get all auth roles |
||
| 74 | * |
||
| 75 | * @return array |
||
| 76 | */ |
||
| 77 | 9 | public function getRoles() |
|
| 87 | |||
| 88 | /** |
||
| 89 | * Check if the current user is logged in and has specified role. |
||
| 90 | * |
||
| 91 | * <code> |
||
| 92 | * if (!$auth->is('manager')) { |
||
| 93 | * http_response_code(403); // Forbidden |
||
| 94 | * echo "You are not allowed to view this page"; |
||
| 95 | * exit(); |
||
| 96 | * } |
||
| 97 | * </code> |
||
| 98 | * |
||
| 99 | * @param string $group |
||
| 100 | * @return boolean |
||
| 101 | */ |
||
| 102 | 7 | public function is($group) |
|
| 119 | } |
||
| 120 |
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.