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    /**
16     * @param string        $name
17     * @param AbstractQuery $filter
18     */
19    public function __construct(string $name, AbstractQuery $filter = null)
20    {
21        parent::__construct($name);
22
23        if (null !== $filter) {
24            $this->setFilter($filter);
25        }
26    }
27
28    /**
29     * Set the filter for this aggregation.
30     *
31     * @param AbstractQuery $filter
32     *
33     * @return $this
34     */
35    public function setFilter(AbstractQuery $filter)
36    {
37        return $this->setParam('filter', $filter);
38    }
39
40    /**
41     * @throws \Elastica\Exception\InvalidException If filter is not set
42     *
43     * @return array
44     */
45    public function toArray(): array
46    {
47        if (!$this->hasParam('filter')) {
48            throw new InvalidException('Filter is required');
49        }
50
51        $array = [
52            'filter' => $this->getParam('filter')->toArray(),
53        ];
54
55        if ($this->_aggs) {
56            $array['aggs'] = $this->_convertArrayable($this->_aggs);
57        }
58
59        return $array;
60    }
61}
62