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 |
||
12 | View Code Duplication | abstract class BaseType implements Type, ArrayAccess, JsonSerializable |
|
|
|||
13 | { |
||
14 | /** @var array */ |
||
15 | protected $properties = []; |
||
16 | |||
17 | public function getContext(): string |
||
21 | |||
22 | public function getType(): string |
||
26 | |||
27 | public function setProperty(string $property, $value) |
||
35 | |||
36 | public function addProperties(array $properties) |
||
44 | |||
45 | public function if($condition, $callback) |
||
53 | |||
54 | public function getProperty(string $property, $default = null) |
||
58 | |||
59 | public function getProperties(): array |
||
63 | |||
64 | public function offsetExists($offset) |
||
68 | |||
69 | public function offsetGet($offset) |
||
73 | |||
74 | public function offsetSet($offset, $value) |
||
78 | |||
79 | public function offsetUnset($offset) |
||
83 | |||
84 | public function toArray(): array |
||
94 | |||
95 | protected function serializeProperty($property) |
||
96 | { |
||
97 | if (is_array($property)) { |
||
98 | return array_map([$this, 'serializeProperty'], $property); |
||
99 | } |
||
100 | |||
101 | if ($property instanceof Type) { |
||
102 | $property = $property->toArray(); |
||
103 | unset($property['@context']); |
||
104 | } |
||
105 | |||
106 | if ($property instanceof DateTimeInterface) { |
||
107 | $property = $property->format(DateTime::ATOM); |
||
108 | } |
||
109 | |||
110 | if (is_object($property) && method_exists($property, '__toString')) { |
||
111 | $property = (string) $property; |
||
112 | } |
||
113 | |||
114 | if (is_object($property)) { |
||
115 | throw new InvalidProperty(); |
||
116 | } |
||
117 | |||
118 | return $property; |
||
119 | } |
||
120 | |||
121 | protected function serializeIdentifier() |
||
128 | |||
129 | public function toScript(): string |
||
133 | |||
134 | public function jsonSerialize() |
||
138 | |||
139 | public function __call(string $method, array $arguments) |
||
143 | |||
144 | public function __toString(): string |
||
148 | } |
||
149 |
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.