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 |
||
16 | trait RequestTrait |
||
17 | { |
||
18 | |||
19 | /** |
||
20 | * Overriding this function to modify the any user input before |
||
21 | * applying the validation rules. |
||
22 | * |
||
23 | * @return array |
||
24 | */ |
||
25 | public function all() |
||
35 | |||
36 | /** |
||
37 | * Overriding this function to throw a custom |
||
38 | * exception instead of the default Laravel exception. |
||
39 | * |
||
40 | * @param \Illuminate\Contracts\Validation\Validator $validator |
||
41 | * |
||
42 | * @return mixed|void |
||
43 | */ |
||
44 | public function failedValidation(Validator $validator) |
||
48 | |||
49 | |||
50 | /** |
||
51 | * Used from the `authorize` function if the Request class. |
||
52 | * To call functions and compare their bool responses to determine |
||
53 | * if the user can proceed with the request or not. |
||
54 | * |
||
55 | * @param array $functions |
||
56 | * |
||
57 | * @return bool |
||
58 | */ |
||
59 | protected function check(array $functions) |
||
93 | |||
94 | /** |
||
95 | * apply validation rules to the ID's in the URL, since Laravel |
||
96 | * doesn't validate them by default! |
||
97 | * |
||
98 | * Now you can use validation riles like this: `'id' => 'required|integer|exists:items,id'` |
||
99 | * |
||
100 | * @param array $requestData |
||
101 | * |
||
102 | * @return array |
||
103 | */ |
||
104 | private function applyValidationRulesToUrlParams(Array $requestData) |
||
114 | |||
115 | /** |
||
116 | * @param $user |
||
117 | * |
||
118 | * @return array |
||
119 | */ |
||
120 | View Code Duplication | private function hasAnyPermissionAccess($user) |
|
135 | |||
136 | /** |
||
137 | * @param $user |
||
138 | * |
||
139 | * @return array |
||
140 | */ |
||
141 | View Code Duplication | private function hasAnyRoleAccess($user) |
|
156 | } |
||
157 |
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
Idable
provides a methodequalsId
that 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.