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 |
||
| 5 | class BooleanGuesser extends AbstractGuesser implements GuesserInterface |
||
| 6 | { |
||
| 7 | public function supports(array $mapping) |
||
| 13 | |||
| 14 | public function transform($str, array $mapping = null) |
||
| 15 | { |
||
| 16 | $str = strtolower($str); |
||
| 17 | |||
| 18 | $formats = [ |
||
| 19 | 'active' => true, |
||
| 20 | 'activated' => true, |
||
| 21 | 'enabled' => true, |
||
| 22 | 'disabled' => false, |
||
| 23 | 'true' => true, |
||
| 24 | 'false' => false, |
||
| 25 | 'yes' => true, |
||
| 26 | 'no' => false, |
||
| 27 | '1' => true, |
||
| 28 | '0' => false, |
||
| 29 | ]; |
||
| 30 | |||
| 31 | View Code Duplication | if (false === array_key_exists($str, $formats)) { |
|
|
|
|||
| 32 | throw new \Exception( |
||
| 33 | sprintf( |
||
| 34 | '"%s" is not a supported format. Supported format : [%s].', |
||
| 35 | $str, |
||
| 36 | implode(', ', array_keys($formats)) |
||
| 37 | ) |
||
| 38 | ); |
||
| 39 | } |
||
| 40 | |||
| 41 | return $formats[$str]; |
||
| 42 | } |
||
| 43 | |||
| 44 | public function fake(array $mapping) |
||
| 48 | |||
| 49 | public function getName() |
||
| 53 | } |
||
| 54 |
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.