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 |
||
11 | class LuosimaoAgent extends Agent implements ContentSms, VoiceCode |
||
12 | { |
||
13 | protected static $smsUrl = 'http://sms-api.luosimao.com/v1/send.json'; |
||
14 | protected static $voiceCodeUrl = 'http://voice-api.luosimao.com/v1/verify.json'; |
||
15 | |||
16 | public function sendContentSms($to, $content) |
||
17 | { |
||
18 | // 签名必须在最后面 |
||
19 | if ($content && preg_match('/(【[\\s\\S]*】)/', $content, $matches)) { |
||
20 | if (isset($matches[0]) && strlen($matches[0])) { |
||
21 | $content = str_replace($matches[0], '', $content) . $matches[0]; |
||
22 | } |
||
23 | } |
||
24 | $result = $this->curlPost(self::$smsUrl, [ |
||
25 | 'mobile' => $to, |
||
26 | 'message' => $content, |
||
27 | ], [ |
||
28 | CURLOPT_HTTPAUTH => CURLAUTH_BASIC, |
||
29 | CURLOPT_USERPWD => "api:key-{$this->apikey}", |
||
30 | ]); |
||
31 | $this->setResult($result); |
||
32 | } |
||
33 | |||
34 | public function sendVoiceCode($to, $code) |
||
35 | { |
||
36 | $result = $this->curlPost(self::$voiceCodeUrl, [ |
||
37 | 'mobile' => $to, |
||
38 | 'code' => $code, |
||
39 | ], [ |
||
40 | CURLOPT_HTTPAUTH => CURLAUTH_BASIC, |
||
41 | CURLOPT_USERPWD => "api:key-{$this->voiceApikey}", |
||
42 | ]); |
||
43 | $this->setResult($result); |
||
44 | } |
||
45 | |||
46 | View Code Duplication | protected function setResult($result) |
|
57 | } |
||
58 |
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.