1<?php
2
3namespace Elastica\Query;
4
5use Elastica\Exception\InvalidException;
6
7/**
8 * Terms query.
9 *
10 * @author Nicolas Ruflin <spam@ruflin.com>
11 * @author Roberto Nygaard <roberto@nygaard.es>
12 *
13 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
14 */
15class Terms extends AbstractQuery
16{
17    /**
18     * Terms.
19     *
20     * @var array Terms
21     */
22    protected $_terms;
23
24    /**
25     * Terms key.
26     *
27     * @var string Terms key
28     */
29    protected $_key;
30
31    /**
32     * Construct terms query.
33     *
34     * @param string $key   Terms key
35     * @param array  $terms Terms list
36     */
37    public function __construct(string $key = '', array $terms = [])
38    {
39        $this->setTerms($key, $terms);
40    }
41
42    /**
43     * Sets key and terms for the query.
44     *
45     * @param string $key   terms key
46     * @param array  $terms terms for the query
47     *
48     * @return $this
49     */
50    public function setTerms(string $key, array $terms): self
51    {
52        $this->_key = $key;
53        $this->_terms = \array_values($terms);
54
55        return $this;
56    }
57
58    /**
59     * Sets key and terms lookup for the query.
60     *
61     * @param string $key         terms key
62     * @param array  $termsLookup terms lookup for the query
63     *
64     * @return $this
65     */
66    public function setTermsLookup(string $key, array $termsLookup): self
67    {
68        $this->_key = $key;
69        $this->_terms = $termsLookup;
70
71        return $this;
72    }
73
74    /**
75     * Adds a single term to the list.
76     *
77     * @param string $term Term
78     *
79     * @return $this
80     */
81    public function addTerm(string $term): self
82    {
83        $this->_terms[] = $term;
84
85        return $this;
86    }
87
88    /**
89     * Sets the minimum matching values.
90     *
91     * @param int|string $minimum Minimum value
92     *
93     * @return $this
94     */
95    public function setMinimumMatch($minimum): self
96    {
97        return $this->setParam('minimum_match', $minimum);
98    }
99
100    /**
101     * {@inheritdoc}
102     */
103    public function toArray(): array
104    {
105        if (empty($this->_key)) {
106            throw new InvalidException('Terms key has to be set');
107        }
108        $this->setParam($this->_key, $this->_terms);
109
110        return parent::toArray();
111    }
112}
113