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 |
||
| 13 | trait SelectTrait |
||
| 14 | { |
||
| 15 | use WhereExtendedTrait; |
||
| 16 | use LimitTrait; |
||
| 17 | |||
| 18 | protected $leftJoin = []; |
||
| 19 | protected $orderBy = []; |
||
| 20 | protected $statement; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * Adds an ORDER BY clause. |
||
| 24 | * |
||
| 25 | * @param string $orderBy |
||
| 26 | * @param string|null $direction |
||
| 27 | * |
||
| 28 | * @return self |
||
| 29 | */ |
||
| 30 | public function orderBy($orderBy, $direction = null) |
||
| 40 | |||
| 41 | /** |
||
| 42 | * Adds a LEFT JOIN clause. |
||
| 43 | * |
||
| 44 | * @param Entity $entity |
||
| 45 | * @param string $on |
||
| 46 | * @param array|null $marks |
||
| 47 | * |
||
| 48 | * @return self |
||
| 49 | */ |
||
| 50 | public function leftJoin(Entity $entity, $on = null, $marks = null) |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Adds new marks to the query. |
||
| 70 | * |
||
| 71 | * @param array $marks |
||
| 72 | * |
||
| 73 | * @return self |
||
| 74 | */ |
||
| 75 | public function marks(array $marks) |
||
| 81 | |||
| 82 | /** |
||
| 83 | * Run the query and return a statement with the result. |
||
| 84 | * |
||
| 85 | * @return PDOStatement |
||
| 86 | */ |
||
| 87 | View Code Duplication | public function run() |
|
| 94 | |||
| 95 | /** |
||
| 96 | * Build and return the query. |
||
| 97 | * |
||
| 98 | * @return string |
||
| 99 | */ |
||
| 100 | public function __toString() |
||
| 131 | |||
| 132 | /** |
||
| 133 | * Generates the fields/tables part of a SELECT query. |
||
| 134 | * |
||
| 135 | * @param string $table |
||
| 136 | * @param array $fields |
||
| 137 | * @param bool $rename |
||
| 138 | * |
||
| 139 | * @return string |
||
| 140 | */ |
||
| 141 | protected static function buildFields($table, array $fields, $rename = false) |
||
| 155 | } |
||
| 156 |
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.