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 |
||
13 | trait RequestTrait |
||
14 | { |
||
15 | |||
16 | /** |
||
17 | * Overriding this function to modify the any user input before |
||
18 | * applying the validation rules. |
||
19 | * |
||
20 | * @return array |
||
21 | */ |
||
22 | public function all() |
||
32 | |||
33 | /** |
||
34 | * Overriding this function to throw a custom |
||
35 | * exception instead of the default Laravel exception. |
||
36 | * |
||
37 | * @param \Illuminate\Contracts\Validation\Validator $validator |
||
38 | * |
||
39 | * @return mixed|void |
||
40 | */ |
||
41 | public function failedValidation(Validator $validator) |
||
45 | |||
46 | |||
47 | /** |
||
48 | * Used from the `authorize` function if the Request class. |
||
49 | * To call functions and compare their bool responses to determine |
||
50 | * if the user can proceed with the request or not. |
||
51 | * |
||
52 | * @param array $functions |
||
53 | * |
||
54 | * @return bool |
||
55 | */ |
||
56 | protected function check(array $functions) |
||
90 | |||
91 | /** |
||
92 | * apply validation rules to the ID's in the URL, since Laravel |
||
93 | * doesn't validate them by default! |
||
94 | * |
||
95 | * Now you can use validation riles like this: `'id' => 'required|integer|exists:items,id'` |
||
96 | * |
||
97 | * @param array $requestData |
||
98 | * |
||
99 | * @return array |
||
100 | */ |
||
101 | private function mergeUrlParametersWithRequestData(Array $requestData) |
||
111 | |||
112 | /** |
||
113 | * @param $user |
||
114 | * |
||
115 | * @return array |
||
116 | */ |
||
117 | View Code Duplication | private function hasAnyPermissionAccess($user) |
|
132 | |||
133 | /** |
||
134 | * @param $user |
||
135 | * |
||
136 | * @return array |
||
137 | */ |
||
138 | View Code Duplication | private function hasAnyRoleAccess($user) |
|
153 | } |
||
154 |
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.