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 |
||
| 24 | trait ByLevel |
||
| 25 | { |
||
| 26 | /** |
||
| 27 | * Get the authenticated user |
||
| 28 | * |
||
| 29 | * @return User |
||
| 30 | */ |
||
| 31 | abstract public function user(); |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Get all access levels. |
||
| 35 | * |
||
| 36 | * @return array |
||
| 37 | */ |
||
| 38 | abstract protected function getAccessLevels(); |
||
| 39 | |||
| 40 | /** |
||
| 41 | * Get access level by name. |
||
| 42 | * |
||
| 43 | * @param string|int $role |
||
| 44 | * @return int |
||
| 45 | * @throws DomainException for unknown level names |
||
| 46 | */ |
||
| 47 | 11 | public function getLevel($role) |
|
| 66 | |||
| 67 | /** |
||
| 68 | * Get all authz roles |
||
| 69 | * |
||
| 70 | * @return array |
||
| 71 | */ |
||
| 72 | 11 | public function getRoles() |
|
| 82 | |||
| 83 | /** |
||
| 84 | * Check if the current user is logged in and has specified role. |
||
| 85 | * |
||
| 86 | * <code> |
||
| 87 | * if (!$auth->is('manager')) { |
||
| 88 | * http_response_code(403); // Forbidden |
||
| 89 | * echo "You are not allowed to view this page"; |
||
| 90 | * exit(); |
||
| 91 | * } |
||
| 92 | * </code> |
||
| 93 | * |
||
| 94 | * @param string|int $role |
||
| 95 | * @return boolean |
||
| 96 | */ |
||
| 97 | 9 | public function is($role) |
|
| 122 | } |
||
| 123 |
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.