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 |
||
| 15 | class ObjectSlicer |
||
| 16 | { |
||
| 17 | /** |
||
| 18 | * Make slice |
||
| 19 | * |
||
| 20 | * @param object|array $value Value |
||
| 21 | * @param string $path Path |
||
| 22 | * @return object|array |
||
|
|
|||
| 23 | * |
||
| 24 | * @throws \InvalidArgumentException |
||
| 25 | */ |
||
| 26 | 42 | public function slice($value, $path) |
|
| 34 | |||
| 35 | /** |
||
| 36 | * Make and merge slices |
||
| 37 | * |
||
| 38 | * @param object|array $value Value |
||
| 39 | * @param array $paths Paths |
||
| 40 | * @return object|array |
||
| 41 | * |
||
| 42 | * @throws \InvalidArgumentException |
||
| 43 | */ |
||
| 44 | 38 | public function sliceMulti($value, array $paths) |
|
| 67 | |||
| 68 | /** |
||
| 69 | * Make slice recursive |
||
| 70 | * |
||
| 71 | * @param object|array $value Value |
||
| 72 | * @param array $keys Keys |
||
| 73 | * @return object|array |
||
| 74 | */ |
||
| 75 | 78 | private function sliceRecursive($value, array $keys) |
|
| 106 | |||
| 107 | /** |
||
| 108 | * Merge slices |
||
| 109 | * |
||
| 110 | * @param object|array $dst Dst |
||
| 111 | * @param object|array $src Src |
||
| 112 | * @return void |
||
| 113 | */ |
||
| 114 | 34 | private function mergeSliceRecursive($dst, $src) |
|
| 132 | |||
| 133 | /** |
||
| 134 | * Normalize paths |
||
| 135 | * |
||
| 136 | * It removes duplicates: |
||
| 137 | * ["a.b", "b.c.d", "c.d", "a", "b"] -> ["a", "b", "c.d"] |
||
| 138 | * |
||
| 139 | * @param array $paths Paths |
||
| 140 | * @return array |
||
| 141 | */ |
||
| 142 | 38 | private function normalizePaths(array $paths) |
|
| 155 | } |
||
| 156 |
This check looks for the generic type
arrayas a return type and suggests a more specific type. This type is inferred from the actual code.