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 |
||
| 14 | trait RequestTrait |
||
| 15 | { |
||
| 16 | |||
| 17 | /** |
||
| 18 | * Overriding this function to modify the any user input before |
||
| 19 | * applying the validation rules. |
||
| 20 | * |
||
| 21 | * @return array |
||
| 22 | */ |
||
| 23 | public function all() |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Overriding this function to throw a custom |
||
| 36 | * exception instead of the default Laravel exception. |
||
| 37 | * |
||
| 38 | * @param \Illuminate\Contracts\Validation\Validator $validator |
||
| 39 | * |
||
| 40 | * @return mixed|void |
||
| 41 | */ |
||
| 42 | public function failedValidation(Validator $validator) |
||
| 50 | |||
| 51 | |||
| 52 | /** |
||
| 53 | * Used from the `authorize` function if the Request class. |
||
| 54 | * To call functions and compare their bool responses to determine |
||
| 55 | * if the user can proceed with the request or not. |
||
| 56 | * |
||
| 57 | * @param array $functions |
||
| 58 | * |
||
| 59 | * @return bool |
||
| 60 | */ |
||
| 61 | protected function check(array $functions) |
||
| 95 | |||
| 96 | /** |
||
| 97 | * apply validation rules to the ID's in the URL, since Laravel |
||
| 98 | * doesn't validate them by default! |
||
| 99 | * |
||
| 100 | * Now you can use validation riles like this: `'id' => 'required|integer|exists:items,id'` |
||
| 101 | * |
||
| 102 | * @param array $requestData |
||
| 103 | * |
||
| 104 | * @return array |
||
| 105 | */ |
||
| 106 | private function mergeUrlParametersWithRequestData(Array $requestData) |
||
| 116 | |||
| 117 | /** |
||
| 118 | * @param $user |
||
| 119 | * |
||
| 120 | * @return array |
||
| 121 | */ |
||
| 122 | View Code Duplication | private function hasAnyPermissionAccess($user) |
|
| 137 | |||
| 138 | /** |
||
| 139 | * @param $user |
||
| 140 | * |
||
| 141 | * @return array |
||
| 142 | */ |
||
| 143 | View Code Duplication | private function hasAnyRoleAccess($user) |
|
| 158 | } |
||
| 159 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.