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 |
||
7 | class Promocodes |
||
8 | { |
||
9 | /** |
||
10 | * Generated codes will be saved here |
||
11 | * to be validated later. |
||
12 | * |
||
13 | * @var array |
||
14 | */ |
||
15 | private $codes = []; |
||
16 | |||
17 | /** |
||
18 | * Length of code will be calculated from asterisks you have |
||
19 | * set as mask in your config file. |
||
20 | * |
||
21 | * @var int |
||
22 | */ |
||
23 | private $length; |
||
24 | |||
25 | /** |
||
26 | * Promocodes constructor. |
||
27 | */ |
||
28 | public function __construct() |
||
33 | |||
34 | /** |
||
35 | * Here will be generated single code using your parameters from config. |
||
36 | * |
||
37 | * @return string |
||
38 | */ |
||
39 | private function generate() |
||
71 | |||
72 | /** |
||
73 | * Generate prefix with separator for promocode. |
||
74 | * |
||
75 | * @return string |
||
76 | */ |
||
77 | private function getPrefix() |
||
81 | |||
82 | /** |
||
83 | * Generate suffix with separator for promocode. |
||
84 | * |
||
85 | * @return string |
||
86 | */ |
||
87 | private function getSuffix() |
||
91 | |||
92 | /** |
||
93 | * Your code will be validated to be unique for one request. |
||
94 | * |
||
95 | * @param $collection |
||
96 | * @param $new |
||
97 | * |
||
98 | * @return bool |
||
99 | */ |
||
100 | private function validate($collection, $new) |
||
104 | |||
105 | /** |
||
106 | * Generates promocodes as many as you wish. |
||
107 | * |
||
108 | * @param int $amount |
||
109 | * |
||
110 | * @return array |
||
111 | */ |
||
112 | public function output($amount = 1) |
||
128 | |||
129 | /** |
||
130 | * Save promocodes into database |
||
131 | * Successful insert returns generated promocodes |
||
132 | * Fail will return NULL. |
||
133 | * |
||
134 | * @param int $amount |
||
135 | * @param null $reward |
||
136 | * @param array $data |
||
137 | * |
||
138 | * @return static |
||
139 | */ |
||
140 | View Code Duplication | public function create($amount = 1, $reward = null, array $data = []) |
|
160 | |||
161 | /** |
||
162 | * Check promocode in database if it is valid. |
||
163 | * |
||
164 | * @param $code |
||
165 | * |
||
166 | * @return bool |
||
167 | */ |
||
168 | public function check($code) |
||
172 | |||
173 | /** |
||
174 | * Apply promocode to user that it's used from now. |
||
175 | * |
||
176 | * @param $code |
||
177 | * |
||
178 | * @return mixed |
||
179 | */ |
||
180 | public function apply($code) |
||
197 | } |
||
198 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: