summaryrefslogtreecommitdiff
path: root/vendor/ruflin/elastica/lib/Elastica/Aggregation/Filters.php
blob: e0fbf0609893c889c1c2124cac06818f410ee92c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
namespace Elastica\Aggregation;

use Elastica\Filter\AbstractFilter;

/**
 * Class Filters.
 *
 * @link http://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filters-aggregation.html
 */
class Filters extends AbstractAggregation
{
    /**
     * Add a filter.
     *
     * If a name is given, it will be added as a key, otherwise considered as an anonymous filter
     *
     * @param AbstractFilter $filter
     * @param string         $name
     *
     * @return $this
     */
    public function addFilter(AbstractFilter $filter, $name = '')
    {
        if (empty($name)) {
            $filterArray[] = $filter->toArray();
        } else {
            $filterArray[$name] = $filter->toArray();
        }

        return $this->addParam('filters', $filterArray);
    }

    /**
     * @return array
     */
    public function toArray()
    {
        $array = array();
        $filters = $this->getParam('filters');

        foreach ($filters as $filter) {
            // Detect between anonymous filters and named ones
            $key = key($filter);

            if (is_string($key)) {
                $array['filters']['filters'][$key] = current($filter);
            } else {
                $array['filters']['filters'][] = current($filter);
            }
        }

        if ($this->_aggs) {
            $array['aggs'] = $this->_aggs;
        }

        return $array;
    }
}