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 |
||
| 11 | class DataEnricher |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * Default processors |
||
| 15 | * @var array |
||
| 16 | */ |
||
| 17 | public static $defaultProcessors = [ |
||
| 18 | '_ref' => Processor\Reference::class, |
||
| 19 | '_switch' => Processor\SwitchChoose::class, |
||
| 20 | '_src' => Processor\Http::class, |
||
| 21 | '_merge' => Processor\Merge::class, |
||
| 22 | '_jmespath' => Processor\JmesPath::class, |
||
| 23 | '_tpl' => Processor\Mustache::class |
||
| 24 | ]; |
||
| 25 | |||
| 26 | |||
| 27 | /** |
||
| 28 | * @var object |
||
| 29 | */ |
||
| 30 | protected $source; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Processors, applied in specified order. |
||
| 34 | * |
||
| 35 | * @var DataEnricher\Processor[] |
||
| 36 | */ |
||
| 37 | public $processors; |
||
| 38 | |||
| 39 | |||
| 40 | /** |
||
| 41 | * Class constructor |
||
| 42 | * |
||
| 43 | * @param object $source Data source |
||
| 44 | */ |
||
| 45 | public function __construct($source) |
||
| 62 | |||
| 63 | /** |
||
| 64 | * Get the source object |
||
| 65 | * |
||
| 66 | * @return object |
||
| 67 | */ |
||
| 68 | public function getSource() |
||
| 72 | |||
| 73 | |||
| 74 | /** |
||
| 75 | * Invoke enricher |
||
| 76 | * |
||
| 77 | * @param array|object|string $target Target or dot key path |
||
| 78 | */ |
||
| 79 | public function applyTo($target) |
||
| 91 | |||
| 92 | /** |
||
| 93 | * Find nodes that have processing instructions |
||
| 94 | * |
||
| 95 | * @param array|object $target |
||
| 96 | * @return array|object |
||
| 97 | */ |
||
| 98 | public function findNodes(&$target) |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Replace nodes with their results |
||
| 118 | * |
||
| 119 | * @param array|object $target |
||
| 120 | */ |
||
| 121 | public function applyNodeResults(&$target) |
||
| 133 | |||
| 134 | /** |
||
| 135 | * Enrich object |
||
| 136 | * |
||
| 137 | * @param object $subject |
||
| 138 | */ |
||
| 139 | public static function process($subject) |
||
| 144 | } |
||
| 145 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.