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 |
||
| 8 | class JoinGenerator |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * @var array |
||
| 12 | */ |
||
| 13 | private $uniqueJoinNameCache = []; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @var Field[] |
||
| 17 | */ |
||
| 18 | private $queryBuilderDataSourceFields; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * @var Join[] |
||
| 22 | */ |
||
| 23 | private $joins; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @var string |
||
| 27 | */ |
||
| 28 | private $fromAlias; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @var Join[][] |
||
| 32 | */ |
||
| 33 | private $joinCache = []; |
||
| 34 | |||
| 35 | /** |
||
| 36 | * @param array $queryBuilderDataSourceFields |
||
| 37 | * @param $fromAlias |
||
| 38 | * @param RequiredFieldsExtractor $requiredFieldsExtractor |
||
| 39 | */ |
||
| 40 | public function __construct(array $queryBuilderDataSourceFields, $fromAlias, RequiredFieldsExtractor $requiredFieldsExtractor) |
||
| 46 | |||
| 47 | /** |
||
| 48 | * Generate the needed joins given a $query. This function will build a dependency tree and |
||
| 49 | * walk it recursively to generate an ordered list of Join statements. |
||
| 50 | * |
||
| 51 | * @param Query $query |
||
| 52 | * |
||
| 53 | * @return Join[] |
||
| 54 | */ |
||
| 55 | View Code Duplication | public function generate(Query $query) |
|
| 64 | |||
| 65 | /** |
||
| 66 | * @param Query $query |
||
| 67 | * |
||
| 68 | * @return Join[] |
||
| 69 | */ |
||
| 70 | protected function build(Query $query) |
||
| 90 | |||
| 91 | /** |
||
| 92 | * Builds a tree of dependencies between entity fields, relating what joins |
||
| 93 | * are needed for each selected field in the query. |
||
| 94 | * |
||
| 95 | * This action is performed recursively. |
||
| 96 | * |
||
| 97 | * @param array $elements |
||
| 98 | * |
||
| 99 | * @return array |
||
| 100 | */ |
||
| 101 | protected function generateJoinDependencyTree(array $elements) |
||
| 120 | |||
| 121 | /** |
||
| 122 | * Walks a node of the dependency tree, recursively generating an ordered list on Joins |
||
| 123 | * that is stored in the $this->joins cache. |
||
| 124 | * |
||
| 125 | * @param $parentUniqueIdentifier |
||
| 126 | * @param $node |
||
| 127 | * @param $descendants |
||
| 128 | * @param array $completePath |
||
| 129 | */ |
||
| 130 | protected function walkDependencyTreeNode($parentUniqueIdentifier, $node, $descendants, $completePath = []) |
||
| 143 | } |
||
| 144 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: