-
Notifications
You must be signed in to change notification settings - Fork 732
/
Terms.php
101 lines (84 loc) · 2.24 KB
/
Terms.php
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace Elastica\Query;
use Elastica\Exception\InvalidException;
/**
* Terms query.
*
* @author Nicolas Ruflin <spam@ruflin.com>
* @author Roberto Nygaard <roberto@nygaard.es>
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
*/
class Terms extends AbstractQuery
{
/**
* @var string
*/
private $field;
/**
* @var array<float|int|string>
*/
private $terms;
/**
* @var string[]|null
*/
private $lookup;
/**
* @param array<bool|float|int|string> $terms Terms list, leave empty if building a terms-lookup query
*/
public function __construct(string $field, array $terms = [])
{
if (empty($field)) {
throw new InvalidException('Terms field name has to be set');
}
$this->field = $field;
$this->terms = $terms;
}
/**
* Sets terms for the query.
*
* @param array<bool|float|int|string>
*/
public function setTerms(array $terms): self
{
$this->terms = $terms;
return $this;
}
/**
* Adds a single term to the list.
*
* @param bool|float|int|string $term
*/
public function addTerm($term): self
{
if (!\is_scalar($term)) {
throw new \TypeError(\sprintf('Argument 1 passed to "%s()" must be a scalar, %s given.', __METHOD__, \is_object($term) ? \get_class($term) : \gettype($term)));
}
$this->terms[] = $term;
return $this;
}
public function setTermsLookup(string $index, string $id, string $path): self
{
$this->lookup = [
'index' => $index,
'id' => $id,
'path' => $path,
];
return $this;
}
/**
* {@inheritdoc}
*/
public function toArray(): array
{
if (null !== $this->lookup && \count($this->terms)) {
throw new InvalidException('Unable to build Terms query: only one of terms or lookup properties should be set');
}
if (null !== $this->lookup) {
$this->setParam($this->field, $this->lookup);
} else {
$this->setParam($this->field, $this->terms);
}
return parent::toArray();
}
}