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 |
||
30 | trait QueryTrait |
||
31 | { |
||
32 | /** |
||
33 | * Returns public users. |
||
34 | * |
||
35 | * @return Eloquent\Collection |
||
36 | */ |
||
37 | 5 | public function activeUsers() |
|
38 | { |
||
39 | 5 | return $this->with('role') |
|
|
|||
40 | 5 | ->where('private', '=', false) |
|
41 | 5 | ->orderBy('firstname', 'ASC')->get(); |
|
42 | } |
||
43 | |||
44 | /** |
||
45 | * Returns user projects with activities details eager loaded. |
||
46 | * |
||
47 | * @param int $status |
||
48 | * |
||
49 | * @return Relations\HasMany |
||
50 | */ |
||
51 | 10 | public function projectsWidthActivities($status = Project::STATUS_OPEN) |
|
75 | |||
76 | /** |
||
77 | * Returns projects with issues details eager loaded. |
||
78 | * |
||
79 | * @param int $status |
||
80 | * |
||
81 | * @return Relations\HasMany |
||
82 | */ |
||
83 | 1 | public function projectsWidthIssues($status = Project::STATUS_OPEN) |
|
101 | |||
102 | /** |
||
103 | * Returns collection of issues grouped by tags. |
||
104 | * |
||
105 | * @param $tagIds |
||
106 | * @param int $projectId |
||
107 | * |
||
108 | * @return mixed |
||
109 | */ |
||
110 | 1 | public function issuesGroupByTags($tagIds, $projectId = null) |
|
111 | { |
||
112 | 1 | $assignedOrCreate = $this->isUser() ? 'issuesCreatedBy' : 'issues'; |
|
113 | 1 | $issues = $this->$assignedOrCreate() |
|
114 | 1 | ->with('user', 'tags') |
|
115 | 1 | ->where('status', '=', Project\Issue::STATUS_OPEN) |
|
116 | 1 | ->whereIn('projects_issues_tags.tag_id', $tagIds) |
|
117 | 1 | ->join('projects_issues_tags', 'issue_id', '=', 'id') |
|
118 | 1 | ->orderBy('id'); |
|
119 | |||
120 | // Limit by project id |
||
121 | 1 | if ($projectId > 0) { |
|
122 | 1 | $issues->where('project_id', '=', $projectId); |
|
123 | 1 | } |
|
124 | |||
125 | 1 | $issues = $issues->get()->groupBy(function (Project\Issue $issue) { |
|
126 | 1 | return $issue->getStatusTag()->name; |
|
127 | 1 | }); |
|
128 | |||
129 | 1 | return $issues; |
|
130 | } |
||
131 | |||
132 | /** |
||
133 | * Load user permissions. |
||
134 | * |
||
135 | * @return Eloquent\Collection |
||
136 | */ |
||
137 | 64 | protected function loadPermissions() |
|
145 | } |
||
146 |
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.