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 |
||
| 23 | * @link http://goo.gl/tG7ciG |
||
| 24 | */ |
||
| 25 | class CardinalityAggregation extends AbstractAggregation |
||
| 26 | { |
||
| 27 | use MetricTrait; |
||
| 28 | |||
| 29 | use ScriptAwareTrait; |
||
| 30 | |||
| 31 | private ?int $precisionThreshold = null; |
||
|
|
|||
| 32 | |||
| 33 | private ?bool $rehash = null; |
||
| 34 | |||
| 35 | /** |
||
| 36 | * {@inheritdoc} |
||
| 37 | */ |
||
| 38 | public function getArray(): array |
||
| 39 | { |
||
| 40 | $out = array_filter( |
||
| 41 | [ |
||
| 42 | 'field' => $this->getField(), |
||
| 43 | 'script' => $this->getScript(), |
||
| 44 | 'precision_threshold' => $this->getPrecisionThreshold(), |
||
| 45 | 'rehash' => $this->isRehash(), |
||
| 46 | ], |
||
| 47 | fn(mixed $val): bool => $val || is_bool($val) |
||
| 48 | ); |
||
| 49 | |||
| 50 | $this->checkRequiredFields($out); |
||
| 51 | |||
| 52 | return $out; |
||
| 53 | } |
||
| 54 | |||
| 55 | public function setPrecisionThreshold(?int $precision): static |
||
| 56 | { |
||
| 57 | $this->precisionThreshold = $precision; |
||
| 58 | |||
| 59 | return $this; |
||
| 60 | } |
||
| 61 | |||
| 62 | public function getPrecisionThreshold(): ?int |
||
| 63 | { |
||
| 64 | return $this->precisionThreshold; |
||
| 65 | } |
||
| 66 | |||
| 67 | public function isRehash(): ?bool |
||
| 68 | { |
||
| 69 | return $this->rehash; |
||
| 70 | } |
||
| 71 | |||
| 72 | public function setRehash(?bool $rehash): static |
||
| 73 | { |
||
| 74 | $this->rehash = $rehash; |
||
| 75 | |||
| 76 | return $this; |
||
| 77 | } |
||
| 78 | |||
| 79 | public function getType(): string |
||
| 80 | { |
||
| 81 | return 'cardinality'; |
||
| 82 | } |
||
| 83 | |||
| 84 | private function checkRequiredFields(array $fields): void |
||
| 85 | { |
||
| 86 | if (!array_key_exists('field', $fields) && !array_key_exists('script', $fields)) { |
||
| 87 | throw new \LogicException('Cardinality aggregation must have field or script set.'); |
||
| 88 | } |
||
| 89 | } |
||
| 90 | } |
||
| 91 |