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