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 | abstract class DataTransferObject |
||
11 | { |
||
12 | /** @var bool */ |
||
13 | protected $ignoreMissing = false; |
||
14 | |||
15 | /** @var array */ |
||
16 | protected $exceptKeys = []; |
||
17 | |||
18 | /** @var array */ |
||
19 | protected $onlyKeys = []; |
||
20 | |||
21 | /** |
||
22 | * @param array $parameters |
||
23 | * |
||
24 | * @return \Spatie\DataTransferObject\ImmutableDataTransferObject|static |
||
25 | */ |
||
26 | public static function immutable(array $parameters = []): ImmutableDataTransferObject |
||
30 | |||
31 | /** |
||
32 | * @param array $arrayOfParameters |
||
33 | * |
||
34 | * @return \Spatie\DataTransferObject\ImmutableDataTransferObject[]|static[] |
||
35 | */ |
||
36 | public static function arrayOf(array $arrayOfParameters): array |
||
45 | |||
46 | public function __construct(array $parameters = []) |
||
86 | |||
87 | View Code Duplication | public function all(): array |
|
101 | |||
102 | /** |
||
103 | * @param string ...$keys |
||
104 | * |
||
105 | * @return static |
||
106 | */ |
||
107 | public function only(string ...$keys): DataTransferObject |
||
115 | |||
116 | /** |
||
117 | * @param string ...$keys |
||
118 | * |
||
119 | * @return static |
||
120 | */ |
||
121 | public function except(string ...$keys): DataTransferObject |
||
129 | |||
130 | public function toArray(): array |
||
142 | |||
143 | protected function parseArray(array $array): array |
||
164 | |||
165 | /** |
||
166 | * @param \ReflectionClass $class |
||
167 | * |
||
168 | * @return \Spatie\DataTransferObject\FieldValidator[] |
||
169 | */ |
||
170 | protected function getFieldValidators(): array |
||
191 | |||
192 | /** |
||
193 | * @param \Spatie\DataTransferObject\ValueCaster $valueCaster |
||
194 | * @param \Spatie\DataTransferObject\FieldValidator $fieldValidator |
||
195 | * @param mixed $value |
||
196 | * @return mixed |
||
197 | */ |
||
198 | protected function castValue(ValueCaster $valueCaster, FieldValidator $fieldValidator, $value) |
||
206 | |||
207 | protected function getValueCaster(): ValueCaster |
||
211 | } |
||
212 |
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.