IpRange.php 1.9 KB

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