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 |
||
10 | class BitMaskConverter implements IEnumSetConverter |
||
11 | { |
||
12 | /** |
||
13 | * @var string |
||
14 | */ |
||
15 | private $enumClass; |
||
16 | |||
17 | /** |
||
18 | * @var array |
||
19 | */ |
||
20 | private $mapping; |
||
21 | |||
22 | /** |
||
23 | * @param Enum[] $enumValuesMap |
||
24 | */ |
||
25 | 11 | public function __construct($enumValuesMap) |
|
26 | { |
||
27 | 11 | if (!is_array($enumValuesMap) || !count($enumValuesMap)) { |
|
28 | 2 | throw new EnumSetMustContainEnumsException('You have to provide converter mapping.'); |
|
29 | } |
||
30 | 9 | $this->mapping = $this->prepareInnerMapping($enumValuesMap); |
|
31 | 9 | } |
|
32 | |||
33 | /** |
||
34 | * @param int $values |
||
35 | * @return ISet |
||
36 | */ |
||
37 | 5 | View Code Duplication | public function convertToEnumSet($values) |
|
|||
38 | { |
||
39 | 5 | $bitValue = (int) $values; |
|
40 | |||
41 | 5 | $set = []; |
|
42 | 5 | foreach ($this->mapping as $value => $bit) { |
|
43 | 5 | if ($bitValue & $bit) { |
|
44 | 4 | $set[] = call_user_func([$this->enumClass, 'instance'], $value); |
|
45 | 4 | } |
|
46 | 5 | } |
|
47 | 5 | return new ImmutableSet($this->enumClass, $set); |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * @param ISet $enumSet |
||
52 | * @return int |
||
53 | */ |
||
54 | 4 | public function convertFromEnumSet(ISet $enumSet) |
|
63 | |||
64 | /** |
||
65 | * @param string $enumClass |
||
66 | */ |
||
67 | 9 | View Code Duplication | protected function setEnumClass($enumClass) |
74 | |||
75 | /** |
||
76 | * @param $enumValuesMap |
||
77 | * @return array |
||
78 | */ |
||
79 | private function prepareInnerMapping($enumValuesMap) |
||
97 | } |
||
98 |
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.