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 |
||
22 | * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-daterange-aggregation.html |
||
23 | */ |
||
24 | class DateRangeAggregation extends AbstractAggregation |
||
25 | { |
||
26 | use BucketingTrait; |
||
27 | |||
28 | public function __construct( |
||
29 | private string $name, |
||
|
|||
30 | private ?string $field = null, |
||
31 | private ?string $format = null, |
||
32 | private array $ranges = [], |
||
33 | private bool $keyed = false |
||
34 | ) { |
||
35 | parent::__construct($name); |
||
36 | |||
37 | $this->setField($field); |
||
38 | $this->setFormat($format); |
||
39 | $this->setKeyed($keyed); |
||
40 | foreach ($ranges as $range) { |
||
41 | $from = isset($range['from']) ? $range['from'] : null; |
||
42 | $to = isset($range['to']) ? $range['to'] : null; |
||
43 | $key = isset($range['key']) ? $range['key'] : null; |
||
44 | $this->addRange($from, $to, $key); |
||
45 | } |
||
46 | } |
||
47 | |||
48 | public function setKeyed($keyed): static |
||
49 | { |
||
50 | $this->keyed = $keyed; |
||
51 | |||
52 | return $this; |
||
53 | } |
||
54 | |||
55 | public function getFormat(): string |
||
56 | { |
||
57 | return $this->format; |
||
58 | } |
||
59 | |||
60 | public function setFormat($format): static |
||
61 | { |
||
62 | $this->format = $format; |
||
63 | |||
64 | return $this; |
||
65 | } |
||
66 | |||
67 | public function addRange(?string $from = null, ?string $to = null, ?string $key = null): static |
||
68 | { |
||
69 | $range = array_filter( |
||
70 | [ |
||
71 | 'from' => $from, |
||
72 | 'to' => $to, |
||
73 | 'key' => $key, |
||
74 | ], |
||
75 | fn(mixed $v): bool => !is_null($v) |
||
76 | ); |
||
77 | |||
78 | if (empty($range)) { |
||
79 | throw new \LogicException('Either from or to must be set. Both cannot be null.'); |
||
80 | } |
||
81 | |||
82 | $this->ranges[] = $range; |
||
83 | |||
84 | return $this; |
||
85 | } |
||
86 | |||
87 | public function getArray(): array |
||
88 | { |
||
89 | if (!$this->getField() || !$this->getFormat() || empty($this->ranges)) { |
||
90 | throw new \LogicException('Date range aggregation must have field, format set and range added.'); |
||
91 | } |
||
92 | |||
93 | return [ |
||
94 | 'format' => $this->getFormat(), |
||
95 | 'field' => $this->getField(), |
||
96 | 'ranges' => $this->ranges, |
||
97 | 'keyed' => $this->keyed, |
||
98 | ]; |
||
99 | } |
||
100 | |||
101 | public function getType(): string |
||
102 | { |
||
103 | return 'date_range'; |
||
104 | } |
||
105 | } |
||
106 |