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 |
||
16 | class Validation |
||
17 | { |
||
18 | use FilterCheck; |
||
19 | use FilterValidation; |
||
20 | |||
21 | /** |
||
22 | * Mock for enabled filters. |
||
23 | * |
||
24 | * @var array |
||
25 | */ |
||
26 | protected $enabledFilters = []; |
||
27 | |||
28 | /** |
||
29 | * Validation constructor. |
||
30 | * |
||
31 | * @param array $filters |
||
32 | */ |
||
33 | public function __construct($filters = []) |
||
39 | |||
40 | /** |
||
41 | * Check validation for $input |
||
42 | * |
||
43 | * @param string $type |
||
44 | * @param string|array $input |
||
45 | * |
||
46 | * @return boolean|null |
||
47 | */ |
||
48 | public function validation($type = "", $input) |
||
49 | { |
||
50 | switch ($type) { |
||
51 | case 'field_list': |
||
52 | return $this->validFieldList($input); |
||
53 | case 'limit': |
||
54 | return $this->validNumber('limit', $input, 0, 100); |
||
55 | case 'offset': |
||
56 | return $this->validNumber('offset', $input, 0); |
||
57 | case 'filter': |
||
58 | return $this->validFilter($input); |
||
59 | case 'sort': |
||
60 | return $this->validSort($input); |
||
61 | default: |
||
62 | return false; |
||
63 | } |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * Validation for FIELD_LIST parameter. |
||
68 | * |
||
69 | * @param string|array $input |
||
70 | * |
||
71 | * @return bool |
||
72 | */ |
||
73 | protected function validFieldList($input) |
||
87 | |||
88 | /** |
||
89 | * Check if offset or limit is valid. |
||
90 | * |
||
91 | * @param string $type Type of valid (offset or limit) |
||
92 | * @param string|array $input Value |
||
93 | * @param integer $min Min range what value can be |
||
94 | * @param integer $max Max range what value can be |
||
95 | * |
||
96 | * @return $this|bool |
||
97 | */ |
||
98 | protected function validNumber($type, $input, $min, $max = "") |
||
106 | |||
107 | /** |
||
108 | * Validation for FILTER parameter. |
||
109 | * |
||
110 | * @param string|array $input |
||
111 | * |
||
112 | * @return boolean|null |
||
113 | */ |
||
114 | View Code Duplication | protected function validFilter($input) |
|
128 | |||
129 | /** |
||
130 | * Validation for SORT parameter. |
||
131 | * |
||
132 | * @param string|array $input |
||
133 | * |
||
134 | * @return boolean|null |
||
135 | */ |
||
136 | View Code Duplication | protected function validSort($input) |
|
150 | } |
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.