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 |
||
20 | class Plugin extends PluginBase |
||
21 | { |
||
22 | /** |
||
23 | * Returns information about this plugin. |
||
24 | * |
||
25 | * @return array |
||
26 | */ |
||
27 | public function pluginDetails() |
||
36 | |||
37 | public function registerSettings() |
||
51 | |||
52 | public function registerPermissions() |
||
61 | |||
62 | /** |
||
63 | * Boot plugin and register handlers |
||
64 | */ |
||
65 | public function boot() |
||
66 | { |
||
67 | $isLaravel56OrUp = method_exists(\Illuminate\Log\Logger::class, 'getLogger'); |
||
68 | $monolog = $isLaravel56OrUp ? Log::getLogger() : Log::getMonolog(); |
||
69 | |||
70 | $this->setNativeMailerHandler($monolog); |
||
71 | $this->setSlackHandler($monolog); |
||
72 | $this->setSyslogHandler($monolog); |
||
73 | $this->setNewrelicHandler($monolog); |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Set native mailer handler |
||
78 | * |
||
79 | * Formatting lines example (use before pushHandler()): |
||
80 | * $formater = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"); |
||
81 | * $handler->setFormatter($formater); |
||
82 | * |
||
83 | * @param $monolog |
||
84 | * |
||
85 | * @return Logger |
||
86 | */ |
||
87 | private function setNativeMailerHandler($monolog) |
||
109 | |||
110 | /** |
||
111 | * Set handler for Slack messaging app |
||
112 | * |
||
113 | * @param $monolog |
||
114 | * |
||
115 | * @return Logger |
||
116 | */ |
||
117 | private function setSlackHandler($monolog) |
||
134 | |||
135 | /** |
||
136 | * Set handler for Syslog |
||
137 | * |
||
138 | * @param $monolog |
||
139 | * |
||
140 | * @return Logger |
||
141 | */ |
||
142 | View Code Duplication | private function setSyslogHandler($monolog) |
|
157 | |||
158 | /** |
||
159 | * Set handler for New Relic |
||
160 | * |
||
161 | * @param $monolog |
||
162 | * |
||
163 | * @return Logger |
||
164 | */ |
||
165 | View Code Duplication | private function setNewrelicHandler($monolog) |
|
180 | |||
181 | /** |
||
182 | * Check each required field if exist and not empty |
||
183 | * |
||
184 | * @param array $fields |
||
185 | * |
||
186 | * @return bool |
||
187 | */ |
||
188 | private function checkRequiredFields(array $fields) |
||
199 | } |
||
200 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.