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 |
||
17 | abstract class AbstractEnumType extends AbstractType |
||
18 | { |
||
19 | |||
20 | use AutoNameTrait, ConfigAwareTrait; |
||
21 | |||
22 | /** |
||
23 | * ObjectType constructor. |
||
24 | * @param $config |
||
25 | */ |
||
26 | 25 | public function __construct($config = []) |
|
27 | { |
||
28 | 25 | if (empty($config)) { |
|
29 | 25 | $config['name'] = $this->getName(); |
|
30 | 25 | $config['values'] = $this->getValues(); |
|
31 | 25 | } |
|
32 | |||
33 | 25 | $this->config = new EnumTypeConfig($config, $this); |
|
34 | 25 | } |
|
35 | |||
36 | /** |
||
37 | * @return String predefined type kind |
||
38 | */ |
||
39 | 18 | public function getKind() |
|
40 | { |
||
41 | 18 | return TypeMap::KIND_ENUM; |
|
42 | } |
||
43 | |||
44 | /** |
||
45 | * @param $value mixed |
||
46 | * |
||
47 | * @return bool |
||
48 | */ |
||
49 | 8 | public function isValidValue($value) |
|
50 | { |
||
51 | 8 | if (is_null($value)) return true; |
|
52 | 8 | foreach ($this->getConfig()->get('values') as $item) { |
|
53 | 8 | if ($value === $item['name'] || $value === $item['value']) { |
|
54 | 8 | return true; |
|
55 | } |
||
56 | 8 | } |
|
57 | |||
58 | 3 | return false; |
|
59 | } |
||
60 | |||
61 | public function getValidationError($value = null) |
||
62 | { |
||
63 | 2 | $allowedValues = array_map(function (array $value) { |
|
64 | 2 | return sprintf('%s (%s)', $value['name'], $value['value']); |
|
65 | 2 | }, $this->getConfig()->get('values')); |
|
66 | 2 | return sprintf('Value must be one of the allowed ones: %s', implode(', ', $allowedValues)); |
|
67 | } |
||
68 | |||
69 | /** |
||
70 | * @return array |
||
71 | */ |
||
72 | abstract public function getValues(); |
||
73 | |||
74 | 6 | View Code Duplication | public function serialize($value) |
|
|||
75 | { |
||
76 | 6 | foreach ($this->getConfig()->get('values') as $valueItem) { |
|
77 | 6 | if ($value === $valueItem['value']) { |
|
84 | |||
85 | 5 | View Code Duplication | public function parseValue($value) |
95 | |||
96 | 1 | View Code Duplication | public function parseInputValue($value) |
106 | |||
107 | } |
||
108 |
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.