-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRange.php
More file actions
107 lines (83 loc) · 2.14 KB
/
Range.php
File metadata and controls
107 lines (83 loc) · 2.14 KB
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
102
103
104
105
106
107
<?php declare(strict_types = 1);
namespace Spameri\ElasticQuery\Query;
/**
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html
*/
class Range implements LeafQueryInterface
{
private string $field;
/**
* @var int|float|string|\DateTimeInterface|null
*/
private $gte;
/**
* @var int|float|string|\DateTimeInterface|null
*/
private $lte;
private float $boost;
/**
* @param int|float|string|\DateTimeInterface|null $gte
* @param int|float|string|\DateTimeInterface|null $lte
*/
public function __construct(
string $field,
$gte = NULL,
$lte = NULL,
float $boost = 1.0
)
{
if ($gte === NULL && $lte === NULL) {
throw new \Spameri\ElasticQuery\Exception\InvalidArgumentException(
'Range must have at least one border value.'
);
}
if ($lte && $gte && $lte < $gte) {
if ($gte instanceof \DateTimeInterface) {
$gteValue = $gte->format('U');
} else {
$gteValue = $gte;
}
if ($lte instanceof \DateTimeInterface) {
$lteValue = $lte->format('U');
} else {
$lteValue = $lte;
}
throw new \Spameri\ElasticQuery\Exception\InvalidArgumentException(
'Input values does not make range. From: ' . $gteValue . ' To: ' . $lteValue
);
}
$this->field = $field;
$this->gte = $gte;
$this->lte = $lte;
$this->boost = $boost;
}
public function key(): string
{
$gte = $this->gte instanceof \DateTimeInterface ? $this->gte->format('Y-m-d H:i:s') : $this->gte;
$lte = $this->lte instanceof \DateTimeInterface ? $this->lte->format('Y-m-d H:i:s') : $this->lte;
return 'range_' . $this->field . '_' . $gte . '_' . $lte;
}
public function toArray(): array
{
$array = [
'range' => [
$this->field => [
'boost' => $this->boost,
],
],
];
if ($this->gte !== NULL) {
$array['range'][$this->field]['gte'] =
$this->gte instanceof \DateTimeInterface
? $this->gte->format('Y-m-d H:i:s')
: $this->gte;
}
if ($this->lte !== NULL) {
$array['range'][$this->field]['lte'] =
$this->lte instanceof \DateTimeInterface
? $this->lte->format('Y-m-d H:i:s')
: $this->lte;
}
return $array;
}
}