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 |
||
12 | trait AuthorizationTrait |
||
13 | { |
||
14 | |||
15 | /** |
||
16 | * @return \App\Containers\User\Models\User|null |
||
17 | */ |
||
18 | public function getUser() |
||
22 | |||
23 | /** |
||
24 | * @return mixed |
||
25 | */ |
||
26 | public function hasAdminRole() |
||
30 | |||
31 | /** |
||
32 | * @return mixed |
||
33 | */ |
||
34 | public function hasClientRole() |
||
38 | |||
39 | /** |
||
40 | * This function will be called from the Requests (authorize) to check if a user |
||
41 | * has permission to perform an action. |
||
42 | * User can set multiple permissions (separated with "|") and if the user has |
||
43 | * any of the permissions, he will be authorize to proceed with this action. |
||
44 | * |
||
45 | * @return bool |
||
46 | */ |
||
47 | public function hasAccess(User $user = null) |
||
60 | |||
61 | /** |
||
62 | * @param $user |
||
63 | * |
||
64 | * @return array |
||
65 | */ |
||
66 | View Code Duplication | private function hasAnyPermissionAccess($user) |
|
81 | |||
82 | /** |
||
83 | * @param $user |
||
84 | * |
||
85 | * @return array |
||
86 | */ |
||
87 | View Code Duplication | private function hasAnyRoleAccess($user) |
|
102 | } |
||
103 |
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.