1 | <?php |
||
22 | * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-iprange-aggregation.html |
||
23 | */ |
||
24 | class Ipv4RangeAggregation extends AbstractAggregation |
||
25 | { |
||
26 | use BucketingTrait; |
||
27 | |||
28 | public function __construct( |
||
29 | private string $name, |
||
|
|||
30 | private ?string $field = null, |
||
31 | private array $ranges = [] |
||
32 | ) { |
||
33 | parent::__construct($name); |
||
34 | |||
35 | $this->setField($field); |
||
36 | foreach ($ranges as $range) { |
||
37 | if (is_array($range)) { |
||
38 | $from = isset($range['from']) ? $range['from'] : null; |
||
39 | $to = isset($range['to']) ? $range['to'] : null; |
||
40 | $this->addRange($from, $to); |
||
41 | } else { |
||
42 | $this->addMask($range); |
||
43 | } |
||
44 | } |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * Add range to aggregation. |
||
49 | * |
||
50 | * @param string|null $from |
||
51 | * @param string|null $to |
||
52 | * |
||
53 | * @return Ipv4RangeAggregation |
||
54 | */ |
||
55 | public function addRange(?string $from = null, ?string $to = null): static |
||
56 | { |
||
57 | $range = array_filter( |
||
58 | [ |
||
59 | 'from' => $from, |
||
60 | 'to' => $to, |
||
61 | ] |
||
62 | ); |
||
63 | |||
64 | $this->ranges[] = $range; |
||
65 | |||
66 | return $this; |
||
67 | } |
||
68 | |||
69 | public function addMask(string $mask): static |
||
70 | { |
||
71 | $this->ranges[] = ['mask' => $mask]; |
||
72 | |||
73 | return $this; |
||
74 | } |
||
75 | |||
76 | public function getType(): string |
||
77 | { |
||
78 | return 'ip_range'; |
||
79 | } |
||
80 | |||
81 | public function getArray(): array |
||
82 | { |
||
83 | if ($this->getField() && !empty($this->ranges)) { |
||
84 | return [ |
||
85 | 'field' => $this->getField(), |
||
86 | 'ranges' => array_values($this->ranges), |
||
87 | ]; |
||
88 | } |
||
89 | throw new \LogicException('Ip range aggregation must have field set and range added.'); |
||
90 | } |
||
91 | } |
||
92 |