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 |
||
6 | class PassportHelper extends AbstractFormHelper |
||
7 | { |
||
8 | public $passport; |
||
9 | public $language; |
||
10 | |||
11 | public $pass_srs; |
||
12 | public $pass_num; |
||
13 | |||
14 | /** |
||
15 | * @param $passport |
||
16 | * @return $this |
||
17 | */ |
||
18 | 4 | public function set($passport) |
|
24 | |||
25 | /** |
||
26 | * @param $language |
||
27 | * @return $this |
||
28 | */ |
||
29 | 4 | public function setLanguage($language) |
|
30 | { |
||
31 | 4 | if (in_array($language, ['ru', 'ua'])) { |
|
32 | 4 | $this->language = $language; |
|
33 | 4 | } else { |
|
34 | $this->language = false; |
||
35 | } |
||
36 | |||
37 | 4 | return $this; |
|
38 | } |
||
39 | |||
40 | /** |
||
41 | * @return $this |
||
42 | */ |
||
43 | 4 | public function explodePassport() |
|
44 | { |
||
45 | 4 | mb_internal_encoding("UTF-8"); |
|
46 | |||
47 | 4 | $pass_length = mb_strlen($this->passport); |
|
48 | 4 | $is_valid_ru = $this->language == 'ru' && $pass_length == 10; |
|
49 | 4 | $is_valid_ua = $this->language == 'ua' && $pass_length == 8; |
|
50 | |||
51 | 4 | if (!($is_valid_ru || $is_valid_ua)) { |
|
52 | 1 | $this->passport = $this->pass_num = $this->pass_srs = false; |
|
53 | 1 | return $this; |
|
54 | } |
||
55 | |||
56 | 3 | View Code Duplication | if ($is_valid_ru) { |
|
|||
57 | 1 | if ($this->isInteger($this->passport)) { |
|
58 | 1 | $this->pass_srs = mb_substr($this->passport, 0, 4); |
|
59 | 1 | $this->pass_num = mb_substr($this->passport, 4, 6); |
|
60 | 1 | } else { |
|
61 | $this->passport = $this->pass_num = $this->pass_srs = false; |
||
62 | } |
||
63 | 1 | } |
|
64 | |||
65 | 3 | View Code Duplication | if ($is_valid_ua) { |
66 | 2 | $this->pass_srs = mb_substr($this->passport, 0, 2); |
|
67 | 2 | $this->pass_num = mb_substr($this->passport, 2, 6); |
|
68 | 2 | if (!($this->isText($this->pass_srs) && $this->isInteger($this->pass_num))) { |
|
69 | 1 | $this->passport = $this->pass_num = $this->pass_srs = false; |
|
70 | 1 | } |
|
71 | 2 | } |
|
72 | |||
73 | 3 | return $this; |
|
74 | } |
||
75 | |||
76 | /** |
||
77 | * @return mixed |
||
78 | */ |
||
79 | 4 | public function getPassSrc() |
|
83 | |||
84 | /** |
||
85 | * @return mixed |
||
86 | */ |
||
87 | 2 | public function getPassNum() |
|
91 | |||
92 | /** |
||
93 | * @return array |
||
94 | */ |
||
95 | 2 | public function get() |
|
99 | } |
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.