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 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-aggregation.html |
||
| 24 | */ |
||
| 25 | class PercentilesAggregation extends AbstractAggregation |
||
| 26 | { |
||
| 27 | use MetricTrait; |
||
| 28 | |||
| 29 | use ScriptAwareTrait; |
||
| 30 | |||
| 31 | public function __construct( |
||
| 32 | private string $name, |
||
|
|
|||
| 33 | private ?string $field = null, |
||
| 34 | private ?array $percents = null, |
||
| 35 | ?string $script = null, |
||
| 36 | ?int $compression = null |
||
| 37 | ) { |
||
| 38 | parent::__construct($name); |
||
| 39 | |||
| 40 | $this->setField($field); |
||
| 41 | $this->setPercents($percents); |
||
| 42 | $this->setScript($script); |
||
| 43 | $this->setCompression($compression); |
||
| 44 | } |
||
| 45 | |||
| 46 | public function getPercents(): ?array |
||
| 47 | { |
||
| 48 | return $this->percents; |
||
| 49 | } |
||
| 50 | |||
| 51 | public function setPercents(?array $percents): static |
||
| 52 | { |
||
| 53 | $this->percents = $percents; |
||
| 54 | |||
| 55 | return $this; |
||
| 56 | } |
||
| 57 | |||
| 58 | public function getCompression(): ?int |
||
| 59 | { |
||
| 60 | return $this->compression; |
||
| 61 | } |
||
| 62 | |||
| 63 | public function setCompression(?int $compression): static |
||
| 64 | { |
||
| 65 | $this->compression = $compression; |
||
| 66 | |||
| 67 | return $this; |
||
| 68 | } |
||
| 69 | |||
| 70 | public function getType(): string |
||
| 71 | { |
||
| 72 | return 'percentiles'; |
||
| 73 | } |
||
| 74 | |||
| 75 | public function getArray(): array |
||
| 76 | { |
||
| 77 | $out = array_filter( |
||
| 78 | [ |
||
| 79 | 'compression' => $this->getCompression(), |
||
| 80 | 'percents' => $this->getPercents(), |
||
| 81 | 'field' => $this->getField(), |
||
| 82 | 'script' => $this->getScript(), |
||
| 83 | ], |
||
| 84 | fn(mixed $val): bool => $val || is_numeric($val) |
||
| 85 | ); |
||
| 86 | |||
| 87 | $this->isRequiredParametersSet($out); |
||
| 88 | |||
| 89 | return $out; |
||
| 90 | } |
||
| 91 | |||
| 92 | private function isRequiredParametersSet(array $a): void |
||
| 93 | { |
||
| 94 | if (!array_key_exists('field', $a) && !array_key_exists('script', $a)) { |
||
| 95 | throw new \LogicException('Percentiles aggregation must have field or script set.'); |
||
| 96 | } |
||
| 97 | } |
||
| 98 | } |
||
| 99 |