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 |
||
32 | trait CrudTrait |
||
33 | { |
||
34 | /** |
||
35 | * removes a user from a project |
||
36 | * |
||
37 | * @param int $userId |
||
38 | * |
||
39 | * @return mixed |
||
40 | */ |
||
41 | 1 | public function unassignUser($userId) |
|
45 | |||
46 | /** |
||
47 | * Create a new project |
||
48 | * |
||
49 | * @param array $input |
||
50 | * |
||
51 | * @return $this |
||
52 | */ |
||
53 | 42 | public function createProject(array $input = []) |
|
72 | |||
73 | /** |
||
74 | * Update project details |
||
75 | * |
||
76 | * @param array $attributes |
||
77 | * @return bool |
||
78 | */ |
||
79 | 1 | public function update(array $attributes = array()) |
|
89 | |||
90 | /** |
||
91 | * Save the project tags |
||
92 | * |
||
93 | * @param string $tagString |
||
94 | * |
||
95 | * @return bool |
||
96 | */ |
||
97 | public function saveTags($tagString) |
||
98 | { |
||
99 | // Transform the user input tags into tag objects |
||
100 | // Filter out invalid tags entered by the user |
||
101 | $tags = new Collection(array_map('trim', explode(',', $tagString))); |
||
102 | $tags = $tags->transform(function ($tagNameOrId) { |
||
103 | return Tag::find($tagNameOrId); |
||
104 | })->filter(function ($tag) { |
||
105 | return $tag instanceof Tag; |
||
106 | })->merge((new Tag())->getOpenAndCloseTags()); |
||
107 | |||
108 | // Delete all existing |
||
109 | $this->kanbanTags()->detach(); |
||
110 | |||
111 | // Save tags |
||
112 | $kanbanTags = $this->kanbanTags(); |
||
113 | $count = $tags->count(); |
||
114 | View Code Duplication | foreach ($tags as $position => $tag) { |
|
115 | $position = $tag->name === Tag::STATUS_OPEN ? -1 : $position; |
||
116 | $position = $tag->name === Tag::STATUS_CLOSED ? $count+1 : $position; |
||
117 | $kanbanTags->attach([$tag->id => ['position' => $position]]); |
||
118 | } |
||
119 | |||
120 | return true; |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * Assign a user to a project |
||
125 | * |
||
126 | * @param int $userId |
||
127 | * @param int $roleId |
||
128 | * |
||
129 | * @return Project\User |
||
130 | */ |
||
131 | 25 | public function assignUser($userId, $roleId = 0) |
|
138 | |||
139 | /** |
||
140 | * Delete a project |
||
141 | * |
||
142 | * @return void |
||
143 | * |
||
144 | * @throws \Exception |
||
145 | */ |
||
146 | 1 | public function delete() |
|
157 | } |
||
158 |
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.