-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFilterParser.php
261 lines (227 loc) · 9.25 KB
/
FilterParser.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<?php
/*
* This file is part of the ESQL project.
*
* (c) Antoine Bluchet <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Soyuka\ESQL\Filter;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\Persistence\ManagerRegistry;
use JMS\Parser\AbstractParser;
use JMS\Parser\SimpleLexer;
use Soyuka\ESQL\ESQLInterface;
use Soyuka\ESQL\Exception\InvalidArgumentException;
use Soyuka\ESQL\Exception\RuntimeException;
/**
* Implements parsing referenced at https://postgrest.org/en/v7.0.0/api.html#horizontal-filtering-rows
* Example: and=(price.gt.1000,sold.is.false,or(name.not.eq.caddy,sold.is.true)).
*/
final class FilterParser extends AbstractParser implements FilterParserInterface
{
public const T_UNKNOWN = 0;
public const T_AND = 1;
public const T_OR = 2;
public const T_OPEN = 3;
public const T_CLOSE = 4;
public const T_OPERATOR = 5;
public const T_VALUE = 6;
public const T_COLON = 7;
public const T_WORD = 8;
private array $parameterNames = [];
public function __construct(private readonly ESQLInterface $esql, private readonly ManagerRegistry $registry)
{
parent::__construct(new SimpleLexer('/
(and)|(or)
| (\() | (\))
| (gte|gt|lte|lt|neq|eq|ilike|like|in|is|not\.neq|not\.eq|not\.gte|not\.gt|not\.lte|not\.lt|not\.like|not\.ilike|not\.in|not\.is)
| \.
| ([a-zA-Z0-9*]+[^().,]*)
| (,)
/x',
[
self::T_UNKNOWN => 'T_UNKNOWN',
self::T_AND => 'T_AND',
self::T_OR => 'T_OR',
self::T_OPEN => 'T_OPEN',
self::T_CLOSE => 'T_CLOSE',
self::T_OPERATOR => 'T_OPERATOR',
self::T_VALUE => 'T_VALUE',
self::T_COLON => 'T_COLON',
self::T_WORD => 'T_WORD',
],
[$this, 'determineTypeAndValue']
));
}
public function parse($str, $context = null): mixed
{
if (!$context) {
throw new InvalidArgumentException('Parsing a filter without a class as second argument is not possible.');
}
$this->context = $context;
$this->lexer->setInput($str);
$driver = $this->registry->getConnection()->getDriver()->getDatabasePlatform();
$esql = $this->esql->__invoke($context);
$result = '';
$parameters = [];
$openingParenthesis = -1;
$closingParenthesis = -1;
$operator = '';
while ($this->lexer->isNextAny([self::T_COLON, self::T_AND, self::T_OR, self::T_OPEN, self::T_CLOSE])) {
if ($this->lexer->isNext(self::T_AND)) {
$operator = ' AND ';
$result .= $result ? ' AND ' : '';
$this->lexer->moveNext();
} elseif ($this->lexer->isNext(self::T_OR)) {
$operator = ' OR ';
$result .= $result ? ' OR ' : '';
$this->lexer->moveNext();
} elseif ($this->lexer->isNext(self::T_OPEN)) {
$this->lexer->moveNext();
$result .= ++$openingParenthesis < 1 ? '' : '(';
} elseif ($this->lexer->isNext(self::T_CLOSE)) {
$result .= ++$closingParenthesis < 1 ? '' : ')';
$this->lexer->moveNext();
}
if ($this->lexer->isNextAny([self::T_WORD, self::T_COLON])) {
if ($this->lexer->isNext(self::T_COLON)) {
$this->lexer->moveNext();
if ($this->lexer->isNext(self::T_WORD)) {
$result .= $operator;
}
}
if ($this->lexer->isNext(self::T_WORD)) {
[$parameterName, $columnValue] = $this->match(self::T_WORD);
$uniqueParameterName = $this->uniqueParameterName($parameterName);
$sqlOperator = $this->match(self::T_OPERATOR);
// The value is an array
if ($this->lexer->isNext(self::T_OPEN)) {
$result .= "$columnValue $sqlOperator (";
$this->lexer->moveNext();
while (!$this->lexer->isNext(self::T_CLOSE)) {
if ($this->lexer->isNext(self::T_COLON)) {
$result .= ',';
$this->lexer->moveNext();
} elseif ($this->lexer->isNext(self::T_VALUE)) {
$result .= ":$uniqueParameterName";
$parameters[$uniqueParameterName] = $this->match(self::T_VALUE);
$uniqueParameterName = $this->uniqueParameterName($parameterName);
} else {
throw new InvalidArgumentException('Argument malformed');
}
}
$result .= ')';
$this->lexer->moveNext();
continue;
}
$value = $this->match(self::T_VALUE);
if (!$this->supportsSQLClause($sqlOperator, $driver)) {
throw new InvalidArgumentException("The operator '$sqlOperator' is not supported.");
}
if (str_starts_with($sqlOperator, 'IS')) {
if (!\in_array($value, [true, false, null], true)) {
throw new InvalidArgumentException('IS only works with true, false or null.');
}
$result .= "$columnValue $sqlOperator ".(true === $value ? 'TRUE' : (false === $value ? 'FALSE' : 'NULL'));
} else {
$result .= "$columnValue $sqlOperator :$uniqueParameterName";
if (str_contains($sqlOperator, 'LIKE')) {
$value = str_replace('*', '%', $value);
}
$parameters[$uniqueParameterName] = $esql->toSQLValue($parameterName, $value);
}
}
}
}
if (null !== $this->lexer->next) {
$this->syntaxError('end of input');
}
return [$result, $parameters];
}
/**
* Not implemented, we override parse directly.
*/
protected function parseInternal(): void
{
throw new RuntimeException('Can not call parseInternal');
}
private function operatorToSQLCondition(string $condition): string
{
$negation = false;
if (str_starts_with($condition, 'not.')) {
$condition = substr($condition, 4);
$negation = true;
}
return match ($condition) {
'eq' => $negation ? '!=' : '=',
'gt' => $negation ? '<' : '>',
'gte' => $negation ? '<=' : '>=',
'lt' => $negation ? '>' : '<',
'lte' => $negation ? '>=' : '<=',
'neq' => $negation ? '=' : '!=',
'ilike' => $negation ? 'NOT ILIKE' : 'ILIKE',
'like' => $negation ? 'NOT LIKE' : 'LIKE',
'is' => $negation ? 'IS NOT' : 'IS',
'in' => $negation ? 'NOT IN' : 'IN',
default => throw new InvalidArgumentException($condition.' is not supported.'),
};
}
private function uniqueParameterName(string $parameterName): string
{
if (isset($this->parameterNames[$parameterName])) {
return $parameterName.'_'.(++$this->parameterNames[$parameterName]);
}
$this->parameterNames[$parameterName] = 1;
return $parameterName.'_1';
}
/**
* @param mixed $value
*/
public function determineTypeAndValue($value): array
{
$esql = $this->esql->__invoke($this->context);
if ('and' === $value) {
return [self::T_AND, 'and'];
}
if ('or' === $value) {
return [self::T_OR, 'or'];
}
if ('(' === $value) {
return [self::T_OPEN, '('];
}
if (')' === $value) {
return [self::T_CLOSE, ')'];
}
if (1 === preg_match('~^(not\.)?(eq|gt|gte|lte|lt|neq|like|ilike|in|is)$~', (string) $value)) {
return [self::T_OPERATOR, $this->operatorToSQLCondition($value)];
}
if (',' === $value) {
return [self::T_COLON, $value];
}
if (\is_string($value) && ($col = $esql->column($value))) {
return [self::T_WORD, [$value, $col]];
}
if (\is_string($value)) {
$lower = strtolower($value);
if ('true' === $lower) {
$value = true;
} elseif ('false' === $lower) {
$value = false;
} elseif ('null' === $lower) {
$value = null;
}
return [self::T_VALUE, $value];
}
return [self::T_UNKNOWN, $value];
}
private function supportsSQLClause(string $sqlClause, mixed $driver): bool
{
return match ($driver) {
$driver instanceof SqlitePlatform => 'ILIKE' === $sqlClause || 'IS' === $sqlClause ? false : true,
default => true,
};
}
}