-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCondition.php
More file actions
438 lines (371 loc) · 14.4 KB
/
Condition.php
File metadata and controls
438 lines (371 loc) · 14.4 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
<?php
declare(strict_types=1);
namespace Atk4\Data\Model\Scope;
use Atk4\Core\ReadableCaptionTrait;
use Atk4\Data\Exception;
use Atk4\Data\Field;
use Atk4\Data\Model;
use Atk4\Data\Persistence;
use Atk4\Data\Persistence\Sql\Expression;
use Atk4\Data\Persistence\Sql\Expressionable;
use Atk4\Data\Persistence\Sql\Sqlite\Expression as SqliteExpression;
class Condition extends AbstractScope
{
use ReadableCaptionTrait;
/** @var string|Field|Expressionable */
public $key;
/** @var string|null */
public $operator;
/** @var mixed */
public $value;
protected bool $system = false;
public const OPERATOR_EQUALS = '=';
public const OPERATOR_DOESNOT_EQUAL = '!=';
public const OPERATOR_GREATER = '>';
public const OPERATOR_GREATER_EQUAL = '>=';
public const OPERATOR_LESS = '<';
public const OPERATOR_LESS_EQUAL = '<=';
public const OPERATOR_LIKE = 'LIKE';
public const OPERATOR_NOT_LIKE = 'NOT LIKE';
public const OPERATOR_IN = 'IN';
public const OPERATOR_NOT_IN = 'NOT IN';
public const OPERATOR_REGEXP = 'REGEXP';
public const OPERATOR_NOT_REGEXP = 'NOT REGEXP';
/** @var array<string, array<string, string>> */
protected static $operators = [
self::OPERATOR_EQUALS => [
'negate' => self::OPERATOR_DOESNOT_EQUAL,
'label' => 'is equal to',
],
self::OPERATOR_DOESNOT_EQUAL => [
'negate' => self::OPERATOR_EQUALS,
'label' => 'is not equal to',
],
self::OPERATOR_LESS => [
'negate' => self::OPERATOR_GREATER_EQUAL,
'label' => 'is smaller than',
],
self::OPERATOR_GREATER => [
'negate' => self::OPERATOR_LESS_EQUAL,
'label' => 'is greater than',
],
self::OPERATOR_GREATER_EQUAL => [
'negate' => self::OPERATOR_LESS,
'label' => 'is greater or equal to',
],
self::OPERATOR_LESS_EQUAL => [
'negate' => self::OPERATOR_GREATER,
'label' => 'is smaller or equal to',
],
self::OPERATOR_LIKE => [
'negate' => self::OPERATOR_NOT_LIKE,
'label' => 'is like',
],
self::OPERATOR_NOT_LIKE => [
'negate' => self::OPERATOR_LIKE,
'label' => 'is not like',
],
self::OPERATOR_IN => [
'negate' => self::OPERATOR_NOT_IN,
'label' => 'is one of',
],
self::OPERATOR_NOT_IN => [
'negate' => self::OPERATOR_IN,
'label' => 'is not one of',
],
self::OPERATOR_REGEXP => [
'negate' => self::OPERATOR_NOT_REGEXP,
'label' => 'is regular expression',
],
self::OPERATOR_NOT_REGEXP => [
'negate' => self::OPERATOR_REGEXP,
'label' => 'is not regular expression',
],
];
/**
* @param string|Expressionable $key
* @param string|mixed $operator
* @param mixed $value
*/
public function __construct($key, $operator = null, $value = null)
{
if ($key instanceof AbstractScope) {
throw new Exception('Only Scope can contain another conditions');
} elseif ($key instanceof Field) { // for BC
$key = $key->shortName;
} elseif (!is_string($key) && !$key instanceof Expressionable) { // @phpstan-ignore-line
throw new Exception('Field must be a string or an instance of Expressionable');
}
if ('func_num_args'() === 2) {
$value = $operator;
$operator = self::OPERATOR_EQUALS;
}
$this->key = $key;
$this->value = $value;
if ($operator === null) {
// at least MSSQL database always requires an operator
if (!$key instanceof Expressionable) {
throw new Exception('Operator must be specified');
}
} else {
$this->operator = strtoupper($operator);
if (!array_key_exists($this->operator, self::$operators)) {
throw (new Exception('Operator is not supported'))
->addMoreInfo('operator', $operator);
}
}
if (is_array($value)) {
foreach ($value as $v) {
if (is_array($v)) {
throw (new Exception('Multi-dimensional array as condition value is not supported'))
->addMoreInfo('value', $value);
}
}
if (!in_array($this->operator, [
self::OPERATOR_EQUALS,
self::OPERATOR_IN,
self::OPERATOR_DOESNOT_EQUAL,
self::OPERATOR_NOT_IN,
], true)) {
throw (new Exception('Operator is not supported for array condition value'))
->addMoreInfo('operator', $operator)
->addMoreInfo('value', $value);
}
}
}
protected function setSystem(bool $system = true)
{
$this->system = $system;
return $this;
}
protected function onChangeModel(): void
{
$model = $this->getModel();
if ($model !== null) {
// if we have a definitive equal condition set the value as default value for field
// new records will automatically get this value assigned for the field
// TODO: fix when condition is part of OR scope
if ($this->system && $this->isDefiniteValue()) {
// key containing '/' means chained references and it is handled in toQueryArguments method
$field = $this->key;
if (is_string($field) && !str_contains($field, '/')) {
$field = $model->getField($field);
}
// TODO Model/field should not be mutated, see:
// https://github.com/atk4/data/issues/662
// for now, do not set default at least for PK/ID
if ($field instanceof Field && $field->shortName !== $field->getOwner()->idField) {
$field->system = true;
$fakePersistence = new Persistence\Array_();
$valueCloned = $fakePersistence->typecastLoadField($field, $fakePersistence->typecastSaveField($field, $this->value));
$field->default = $valueCloned;
}
}
}
}
/**
* @return array<0|1|2, mixed>
*/
public function toQueryArguments(): array
{
if ($this->isEmpty()) {
return [];
}
$field = $this->key;
$operator = $this->operator;
$value = $this->value;
$model = $this->getModel();
if ($model !== null) {
if (is_string($field)) {
// shorthand for adding conditions on references
// use chained reference names separated by "/"
if (str_contains($field, '/')) {
$references = explode('/', $field);
$field = array_pop($references);
$refModels = [];
$refModel = $model;
foreach ($references as $link) {
$refModel = $refModel->refLink($link);
$refModels[] = $refModel;
}
unset($refModel);
foreach (array_reverse($refModels) as $refModel) {
if ($field === '#') {
if (is_string($value) && $value === (string) (int) $value) {
$value = (int) $value;
}
if ($value === 0) {
$field = $refModel->action('exists');
$value = false;
} elseif ($value === 1 && $operator === self::OPERATOR_GREATER_EQUAL) {
$field = $refModel->action('exists');
$operator = self::OPERATOR_EQUALS;
$value = true;
} else {
$field = $refModel->action('count');
}
} else {
$refModel->addCondition($field, $operator, $value);
$field = $refModel->action('exists');
$operator = self::OPERATOR_EQUALS;
$value = true;
}
}
} else {
$field = $model->getField($field);
}
}
// handle the query arguments using field
if ($field instanceof Field) {
[$field, $operator, $value] = $field->getQueryArguments($operator, $value);
}
// only expression contained in $field
if (!$operator) {
return [$field];
}
// skip explicitly using OPERATOR_EQUALS as in some cases it is transformed to OPERATOR_IN
// for instance in dsql so let exact operator be handled by Persistence
if ($operator === self::OPERATOR_EQUALS) {
return [$field, $value];
}
}
return [$field, $operator, $value];
}
public function isEmpty(): bool
{
return array_filter([$this->key, $this->operator, $this->value]) ? false : true;
}
/**
* Checks if condition sets a definitive scalar value for a field.
*/
protected function isDefiniteValue(): bool
{
return $this->operator === self::OPERATOR_EQUALS && !is_array($this->value)
&& !$this->value instanceof Expressionable
&& !$this->value instanceof Persistence\Array_\Action; // needed to pass hintable tests
}
public function clear()
{
$this->key = null; // @phpstan-ignore-line
$this->operator = null;
$this->value = null;
return $this;
}
public function negate()
{
if (isset(self::$operators[$this->operator]['negate'])) {
$this->operator = self::$operators[$this->operator]['negate'];
} else {
throw (new Exception('Negation of condition is not supported for this operator'))
->addMoreInfo('operator', $this->operator ?? 'no operator');
}
return $this;
}
public function toWords(Model $model = null): string
{
if ($model === null) {
$model = $this->getModel();
}
if ($model === null) {
throw new Exception('Condition must be associated with Model to convert to words');
}
$key = $this->keyToWords($model);
$operator = $this->operatorToWords();
$value = $this->valueToWords($model, $this->value);
return trim($key . ' ' . $operator . ' ' . $value);
}
protected function keyToWords(Model $model): string
{
$words = [];
$field = $this->key;
if (is_string($field)) {
if (str_contains($field, '/')) {
$references = explode('/', $field);
$words[] = $model->getModelCaption();
$field = array_pop($references);
foreach ($references as $link) {
$words[] = 'that has reference ' . $this->readableCaption($link);
$model = $model->refLink($link);
}
$words[] = 'where';
if ($field === '#') {
$words[] = $this->operator ? 'number of records' : 'any referenced record exists';
}
}
if ($model->hasField($field)) {
$field = $model->getField($field);
}
}
if ($field instanceof Field) {
$words[] = $field->getCaption();
} elseif ($field instanceof Expressionable) {
$words[] = $this->valueToWords($model, $field);
}
return implode(' ', array_filter($words));
}
protected function operatorToWords(): string
{
return $this->operator ? self::$operators[$this->operator]['label'] : '';
}
/**
* @param mixed $value
*/
protected function valueToWords(Model $model, $value): string
{
if ($value === null) {
return $this->operator ? 'empty' : '';
}
if (is_array($value)) {
$res = [];
foreach ($value as $v) {
$res[] = $this->valueToWords($model, $v);
}
return implode(' or ', $res);
}
if (is_object($value)) {
if ($value instanceof Field) {
return $value->getOwner()->getModelCaption() . ' ' . $value->getCaption();
}
if ($value instanceof Expressionable) {
return 'expression \'' . $value->getDsqlExpression(new SqliteExpression())->getDebugQuery() . '\'';
}
return 'object ' . print_r($value, true);
}
// handling of scope on references
$field = $this->key;
if (is_string($field)) {
if (str_contains($field, '/')) {
$references = explode('/', $field);
$field = array_pop($references);
foreach ($references as $link) {
$model = $model->refLink($link);
}
}
if ($model->hasField($field)) {
$field = $model->getField($field);
}
}
// use the referenced model title if such exists
$title = null;
if ($field instanceof Field && $field->hasReference()) {
// make sure we set the value in the Model
$model = $model->isEntity() ? clone $model : $model->createEntity();
$model->set($field->shortName, $value);
// then take the title
$title = $model->ref($field->getReference()->link)->getTitle();
if ($title === $value) {
$title = null;
}
}
if (is_bool($value)) {
$valueStr = $value ? 'true' : 'false';
} elseif (is_int($value)) {
$valueStr = (string) $value;
} elseif (is_float($value)) {
$valueStr = Expression::castFloatToString($value);
} else {
$valueStr = '\'' . (string) $value . '\'';
}
return $valueStr . ($title !== null ? ' (\'' . $title . '\')' : '');
}
}