1<?php 2 3namespace Elastica\Aggregation; 4 5use Elastica\Exception\InvalidException; 6 7/** 8 * Class IpRange. 9 * 10 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-iprange-aggregation.html 11 */ 12class IpRange extends AbstractAggregation 13{ 14 use Traits\KeyedTrait; 15 16 /** 17 * @param string $name the name of this aggregation 18 * @param string $field the field on which to perform this aggregation 19 */ 20 public function __construct(string $name, string $field) 21 { 22 parent::__construct($name); 23 $this->setField($field); 24 } 25 26 /** 27 * Set the field for this aggregation. 28 * 29 * @param string $field the name of the document field on which to perform this aggregation 30 * 31 * @return $this 32 */ 33 public function setField(string $field): self 34 { 35 return $this->setParam('field', $field); 36 } 37 38 /** 39 * Add an ip range to this aggregation. 40 * 41 * @param string|null $fromValue a valid ipv4 address. Low end of this range, exclusive (greater than) 42 * @param string|null $toValue a valid ipv4 address. High end of this range, exclusive (less than) 43 * 44 * @throws InvalidException 45 * 46 * @return $this 47 */ 48 public function addRange(?string $fromValue = null, ?string $toValue = null): self 49 { 50 if (null === $fromValue && null === $toValue) { 51 throw new InvalidException('Either fromValue or toValue must be set. Both cannot be null.'); 52 } 53 54 $range = []; 55 if (null !== $fromValue) { 56 $range['from'] = $fromValue; 57 } 58 59 if (null !== $toValue) { 60 $range['to'] = $toValue; 61 } 62 63 return $this->addParam('ranges', $range); 64 } 65 66 /** 67 * Add an ip range in the form of a CIDR mask. 68 * 69 * @param string $mask a valid CIDR mask 70 * 71 * @return $this 72 */ 73 public function addMaskRange(string $mask): self 74 { 75 return $this->addParam('ranges', ['mask' => $mask]); 76 } 77} 78