1<?php
2
3namespace Elastica\Aggregation;
4
5use Elastica\Exception\InvalidException;
6use Elastica\Query\AbstractQuery;
7
8/**
9 * Class Filters.
10 *
11 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filters-aggregation.html
12 */
13class Filters extends AbstractAggregation
14{
15    public const NAMED_TYPE = 1;
16    public const ANONYMOUS_TYPE = 2;
17
18    /**
19     * @var int Type of bucket keys - named, or anonymous
20     */
21    private $_type;
22
23    /**
24     * Add a filter.
25     *
26     * If a name is given, it will be added as a key, otherwise considered as an anonymous filter
27     *
28     * @return $this
29     */
30    public function addFilter(AbstractQuery $filter, ?string $name = null): self
31    {
32        $type = null !== $name ? self::NAMED_TYPE : self::ANONYMOUS_TYPE;
33
34        if ($this->hasParam('filters')
35            && \count($this->getParam('filters'))
36            && $this->_type !== $type
37        ) {
38            throw new InvalidException('Mix named and anonymous keys are not allowed');
39        }
40
41        $this->_type = $type;
42
43        return $this->addParam('filters', $filter, $name);
44    }
45
46    /**
47     * @return $this
48     */
49    public function setOtherBucket(bool $otherBucket): self
50    {
51        return $this->setParam('other_bucket', $otherBucket);
52    }
53
54    /**
55     * @return $this
56     */
57    public function setOtherBucketKey(string $otherBucketKey): self
58    {
59        return $this->setParam('other_bucket_key', $otherBucketKey);
60    }
61}
62