-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathWhere.php
More file actions
513 lines (413 loc) · 15.3 KB
/
Where.php
File metadata and controls
513 lines (413 loc) · 15.3 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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
<?php
/**
* This file is part of FacturaScripts
* Copyright (C) 2023-2025 Carlos Garcia Gomez <carlos@facturascripts.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace FacturaScripts\Core;
use Exception;
use FacturaScripts\Core\Base\DataBase;
use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
/**
* Permite crear cláusulas WHERE para consultas SQL.
*
* @author Carlos García Gómez <carlos@facturascripts.com>
*/
final class Where
{
const FIELD_SEPARATOR = '|';
/** @var DataBase */
private static $db;
/** @var string */
public $fields;
/** @var string */
public $operator;
/** @var string */
public $operation;
/** @var Where[] */
public $subWhere;
/** @var bool */
public $useField;
/** @var mixed */
public $value;
public function __construct(string $fields, $value, string $operator = '=', string $operation = 'AND', bool $useField = false)
{
$this->fields = $fields;
$this->value = $value;
$this->operator = $operator;
$this->operation = $operation;
$this->useField = $useField;
}
public function useField(): self
{
$this->useField = true;
return $this;
}
public static function between(string $fields, $value1, $value2): self
{
return new self($fields, [$value1, $value2], 'BETWEEN');
}
public static function column(string $fields, $value, string $operator = '=', string $operation = 'AND'): self
{
return new self($fields, $value, $operator, $operation);
}
public static function eq(string $fields, $value): self
{
return new self($fields, $value, '=');
}
public static function gt(string $fields, $value): self
{
return new self($fields, $value, '>');
}
public static function gte(string $fields, $value): self
{
return new self($fields, $value, '>=');
}
public static function in(string $fields, $values): self
{
return new self($fields, $values, 'IN');
}
public static function isNotNull(string $fields): self
{
return new self($fields, null, 'IS NOT');
}
public static function isNull(string $fields): self
{
return new self($fields, null, 'IS');
}
public static function like(string $fields, string $value): self
{
return new self($fields, $value, 'LIKE');
}
public static function lt(string $fields, $value): self
{
return new self($fields, $value, '<');
}
public static function lte(string $fields, $value): self
{
return new self($fields, $value, '<=');
}
public static function multiSql(array $where): string
{
$sql = '';
foreach ($where as $item) {
// si no es una instancia de Where, lanzamos una excepción
if (!($item instanceof self)) {
throw new Exception('Invalid where clause ' . print_r($item, true));
}
if (!empty($sql)) {
$sql .= ' ' . $item->operation . ' ';
}
if ($item->operator === '(') {
$sql .= '(' . self::multiSql($item->subWhere) . ')';
continue;
}
$sql .= $item->sql();
}
return $sql;
}
public static function multiSqlLegacy(array $where): string
{
$sql = '';
$group = false;
foreach ($where as $key => $item) {
// si es una instancia de DataBaseWhere, lo convertimos a sql
if ($item instanceof DataBaseWhere) {
$dbWhere = new self($item->fields, $item->value, $item->operator, $item->operation, $item->useField ?? false);
if (!empty($sql)) {
$sql .= ' ' . $item->operation . ' ';
}
// si el siguiente elemento es un OR, lo agrupamos
if (!$group && isset($where[$key + 1]) && $where[$key + 1] instanceof DataBaseWhere && $where[$key + 1]->operation === 'OR') {
$sql .= '(';
$group = true;
}
$sql .= $dbWhere->sql();
// si estamos agrupando y el siguiente elemento no es un OR, cerramos el grupo
if ($group && (!isset($where[$key + 1]) || !($where[$key + 1] instanceof DataBaseWhere) || $where[$key + 1]->operation !== 'OR')) {
$sql .= ')';
$group = false;
}
continue;
}
// si no es una instancia de Where, lanzamos una excepción
if (!($item instanceof self)) {
throw new Exception('Invalid where clause ' . print_r($item, true));
}
if (!empty($sql)) {
$sql .= ' ' . $item->operation . ' ';
}
if ($item->operator === '(') {
$sql .= '(' . self::multiSql($item->subWhere) . ')';
continue;
}
$sql .= $item->sql();
}
return empty($sql) ? '' : ' WHERE ' . $sql;
}
public static function notBetween(string $fields, $value1, $value2): self
{
return new self($fields, [$value1, $value2], 'NOT BETWEEN');
}
public static function notEq(string $fields, $value): self
{
return new self($fields, $value, '!=');
}
public static function notIn(string $fields, $values): self
{
return new self($fields, $values, 'NOT IN');
}
public static function notLike(string $fields, string $value): self
{
return new self($fields, $value, 'NOT LIKE');
}
public static function or(string $fields, $value, string $operator = '='): self
{
return new self($fields, $value, $operator, 'OR');
}
public static function orBetween(string $fields, $value1, $value2): self
{
return new self($fields, [$value1, $value2], 'BETWEEN', 'OR');
}
public static function orEq(string $fields, $value): self
{
return new self($fields, $value, '=', 'OR');
}
public static function orGt(string $fields, $value): self
{
return new self($fields, $value, '>', 'OR');
}
public static function orGte(string $fields, $value): self
{
return new self($fields, $value, '>=', 'OR');
}
public static function orIn(string $fields, $values): self
{
return new self($fields, $values, 'IN', 'OR');
}
public static function orIsNotNull(string $fields): self
{
return new self($fields, null, 'IS NOT', 'OR');
}
public static function orIsNull(string $fields): self
{
return new self($fields, null, 'IS', 'OR');
}
public static function orLike(string $fields, string $value): self
{
return new self($fields, $value, 'LIKE', 'OR');
}
public static function orLt(string $fields, $value): self
{
return new self($fields, $value, '<', 'OR');
}
public static function orLte(string $fields, $value): self
{
return new self($fields, $value, '<=', 'OR');
}
public static function orNotBetween(string $fields, $value1, $value2): self
{
return new self($fields, [$value1, $value2], 'NOT BETWEEN', 'OR');
}
public static function orNotEq(string $fields, $value): self
{
return new self($fields, $value, '!=', 'OR');
}
public static function orNotIn(string $fields, $values): self
{
return new self($fields, $values, 'NOT IN', 'OR');
}
public static function orNotLike(string $fields, string $value): self
{
return new self($fields, $value, 'NOT LIKE', 'OR');
}
public static function orRegexp(string $fields, string $value): self
{
return new self($fields, $value, 'REGEXP', 'OR');
}
public static function orSub(array $where): self
{
return self::sub($where, 'OR');
}
public static function orXlike(string $fields, string $value): self
{
return new self($fields, $value, 'XLIKE', 'OR');
}
public static function regexp(string $fields, string $value): self
{
return new self($fields, $value, 'REGEXP');
}
public function sql(): string
{
$fields = explode(self::FIELD_SEPARATOR, $this->fields);
$sql = count($fields) > 1 ? '(' : '';
foreach ($fields as $key => $field) {
if ($key > 0) {
$sql .= ' OR ';
}
switch ($this->operator) {
case '=':
$sql .= is_null($this->value) ?
self::sqlColumn($field) . ' IS NULL' :
self::sqlColumn($field) . ' = ' . $this->sqlValue($this->value);
break;
case '!=':
case '<>':
$sql .= is_null($this->value) ?
self::sqlColumn($field) . ' IS NOT NULL' :
self::sqlColumn($field) . ' ' . $this->operator . ' ' . $this->sqlValue($this->value);
break;
case '>':
case '<':
case '>=':
case '<=':
case 'REGEXP':
$sql .= self::sqlColumn($field) . ' ' . self::db()->getOperator($this->operator) . ' ' . $this->sqlValue($this->value);
break;
case 'IS':
case 'IS NOT':
$sql .= self::sqlColumn($field) . ' ' . $this->operator . ' NULL';
break;
case 'IN':
case 'NOT IN':
$sql .= self::sqlOperatorIn($field, $this->value, $this->operator);
break;
case 'BETWEEN':
case 'NOT BETWEEN':
$sql .= $this->sqlOperatorBetween($field, $this->value, $this->operator);
break;
case 'LIKE':
case 'NOT LIKE':
$sql .= self::sqlOperatorLike($field, $this->value, $this->operator);
break;
case 'XLIKE':
$sql .= self::sqlOperatorXLike($field, $this->value);
break;
}
}
return count($fields) > 1 ? $sql . ')' : $sql;
}
public static function sub(array $where, string $operation = 'AND'): self
{
// comprobamos si el $where es un array de Where
foreach ($where as $item) {
// si no es una instancia de Where, lanzamos una excepción
if (!($item instanceof self)) {
throw new Exception('Invalid where clause ' . print_r($item, true));
}
}
$item = new self('', '', '(', $operation);
$item->subWhere = $where;
return $item;
}
public static function xlike(string $fields, string $value): self
{
return new self($fields, $value, 'XLIKE');
}
private static function db(): DataBase
{
if (empty(self::$db)) {
self::$db = new DataBase();
}
return self::$db;
}
private static function sqlColumn(string $field): string
{
// si lleva paréntesis, no escapamos
if (strpos($field, '(') !== false && strpos($field, ')') !== false) {
return $field;
}
// si empieza por integer, hacemos el cast
if (substr($field, 0, 8) === 'integer:') {
return self::db()->castInteger(substr($field, 8));
}
// si empieza por lower, hacemos el lower
if (substr($field, 0, 6) === 'lower:') {
return 'LOWER(' . self::db()->escapeColumn(substr($field, 6)) . ')';
}
return self::db()->escapeColumn($field);
}
private function sqlOperatorBetween(string $field, $values, string $operator): string
{
// si no es un array, lanzamos una excepción
if (!is_array($values)) {
throw new Exception('Invalid values in where clause ' . print_r($values, true));
}
// si no tiene 2 elementos, lanzamos una excepción
if (count($values) !== 2) {
throw new Exception('Invalid values in where clause ' . print_r($values, true));
}
return self::sqlColumn($field) . ' ' . $operator . ' ' . $this->sqlValue($values[0])
. ' AND ' . $this->sqlValue($values[1]);
}
private static function sqlOperatorIn(string $field, $values, string $operator): string
{
if (is_array($values)) {
$items = [];
foreach ($values as $val) {
$items[] = self::db()->var2str($val);
}
return self::sqlColumn($field) . ' ' . $operator . ' (' . implode(',', $items) . ')';
}
// si comienza por SELECT, lo tratamos como una subconsulta
if (substr(strtoupper($values), 0, 6) === 'SELECT') {
return self::sqlColumn($field) . ' ' . $operator . ' (' . $values . ')';
}
// es un string, separamos los valores por coma
$items = [];
foreach (explode(',', $values) as $val) {
$items[] = self::db()->var2str(trim($val));
}
return self::sqlColumn($field) . ' ' . $operator . ' (' . implode(',', $items) . ')';
}
private static function sqlOperatorLike(string $field, string $value, string $operator): string
{
// si no contiene %, se los añadimos
if (strpos($value, '%') === false) {
return 'LOWER(CONCAT(' . self::sqlColumn($field) . ",'')) " . $operator
. " LOWER('%" . self::db()->escapeString($value) . "%')";
}
// contiene algún comodín
return 'LOWER(CONCAT(' . self::sqlColumn($field) . ",'')) " . $operator
. " LOWER('" . self::db()->escapeString($value) . "')";
}
private static function sqlOperatorXLike(string $field, string $value): string
{
// separamos las palabras en $value
$words = explode(' ', $value);
// si solamente hay una palabra, la tratamos como un like
if (count($words) === 1) {
return '(' . self::sqlOperatorLike($field, $value, 'LIKE') . ')';
}
// si hay más de una palabra, las tratamos como un like con OR
$sql = '';
foreach ($words as $word) {
if (!empty($sql)) {
$sql .= ' AND ';
}
$sql .= self::sqlOperatorLike($field, trim($word), 'LIKE');
}
return '(' . $sql . ')';
}
private function sqlValue($value): string
{
// si empieza por field: lo tratamos como un campo solo si está autorizado
if ($this->useField && substr($value, 0, 6) === 'field:') {
return self::sqlColumn(substr($value, 6));
}
// si no, lo tratamos como un valor
return self::db()->var2str($value);
}
}