1<?php 2 3namespace Elastica\Aggregation; 4 5use Elastica\Exception\InvalidException; 6use Elastica\Query\AbstractQuery; 7 8/** 9 * Class Filter. 10 * 11 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html 12 */ 13class Filter extends AbstractAggregation 14{ 15 public function __construct(string $name, ?AbstractQuery $filter = null) 16 { 17 parent::__construct($name); 18 19 if (null !== $filter) { 20 $this->setFilter($filter); 21 } 22 } 23 24 /** 25 * Set the filter for this aggregation. 26 * 27 * @return $this 28 */ 29 public function setFilter(AbstractQuery $filter): self 30 { 31 return $this->setParam('filter', $filter); 32 } 33 34 /** 35 * @throws InvalidException If filter is not set 36 */ 37 public function toArray(): array 38 { 39 if (!$this->hasParam('filter')) { 40 throw new InvalidException('Filter is required'); 41 } 42 43 $array = [ 44 'filter' => $this->getParam('filter')->toArray(), 45 ]; 46 47 if ($this->_aggs) { 48 $array['aggs'] = $this->_convertArrayable($this->_aggs); 49 } 50 51 return $array; 52 } 53} 54