-
Notifications
You must be signed in to change notification settings - Fork 639
/
Db.php
1876 lines (1649 loc) · 60.2 KB
/
Db.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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\helpers;
use Craft;
use craft\base\Serializable;
use craft\db\Connection;
use craft\db\mysql\Schema as MysqlSchema;
use craft\db\pgsql\Schema as PgsqlSchema;
use craft\db\Query;
use craft\db\QueryParam;
use DateTimeInterface;
use DateTimeZone;
use Money\Money;
use PDO;
use Throwable;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\NotSupportedException;
use yii\db\BatchQueryResult;
use yii\db\Exception as DbException;
use yii\db\ExpressionInterface;
use yii\db\pgsql\Schema as YiiPgqslSchema;
use yii\db\Query as YiiQuery;
use yii\db\QueryInterface;
use yii\db\Schema;
/**
* Class Db
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Db
{
public const SIMPLE_TYPE_NUMERIC = 'numeric';
public const SIMPLE_TYPE_TEXTUAL = 'textual';
/**
* @var array
*/
private static array $_operators = ['not ', '!=', '<=', '>=', '<', '>', '='];
/**
* @var string[] Numeric column types
*/
private static array $_numericColumnTypes = [
Schema::TYPE_TINYINT,
Schema::TYPE_SMALLINT,
Schema::TYPE_INTEGER,
Schema::TYPE_BIGINT,
Schema::TYPE_FLOAT,
Schema::TYPE_DOUBLE,
Schema::TYPE_DECIMAL,
];
/**
* @var string[] Textual column types
*/
private static array $_textualColumnTypes = [
Schema::TYPE_CHAR,
Schema::TYPE_STRING,
Schema::TYPE_TEXT,
// MySQL-specific ones:
MysqlSchema::TYPE_TINYTEXT,
MysqlSchema::TYPE_MEDIUMTEXT,
MysqlSchema::TYPE_LONGTEXT,
MysqlSchema::TYPE_ENUM,
];
/**
* @var array Types of integer columns and how many bytes they can store
*/
private static array $_integerSizeRanges = [
Schema::TYPE_SMALLINT => [-32768, 32767],
Schema::TYPE_INTEGER => [-2147483648, 2147483647],
Schema::TYPE_BIGINT => [-9223372036854775808, 9223372036854775807],
];
/**
* @var array Types of MySQL textual columns and how many bytes they can store
*/
private static array $_mysqlTextSizes = [
MysqlSchema::TYPE_TINYTEXT => 255,
Schema::TYPE_TEXT => 65535,
MysqlSchema::TYPE_MEDIUMTEXT => 16777215,
MysqlSchema::TYPE_LONGTEXT => 4294967295,
];
/**
* Prepares an array or object’s values to be sent to the database.
*
* @param mixed $values The values to be prepared
* @return array The prepared values
*/
public static function prepareValuesForDb(mixed $values): array
{
// Normalize to an array
$values = ArrayHelper::toArray($values, [], false);
foreach ($values as $key => $value) {
$values[$key] = static::prepareValueForDb($value);
}
return $values;
}
/**
* Prepares a value to be sent to the database.
*
* @param mixed $value The value to be prepared
* @param string|null $columnType The type of column the value will be stored in
* @return mixed The prepped value
*/
public static function prepareValueForDb(mixed $value, ?string $columnType = null): mixed
{
// Leave expressions alone
if ($value instanceof ExpressionInterface) {
return $value;
}
// If the object explicitly defines its savable value, use that
if ($value instanceof Serializable) {
return $value->serialize();
}
// Only DateTime objects and ISO-8601 strings should automatically be detected as dates
if ($value instanceof DateTimeInterface || DateTimeHelper::isIso8601($value)) {
return static::prepareDateForDb($value);
}
// If this isn’t a JSON column and the value is an object or array, JSON-encode it
if (is_object($value) || is_array($value)) {
if (in_array($columnType, [Schema::TYPE_JSON, YiiPgqslSchema::TYPE_JSONB])) {
return ArrayHelper::toArray($value);
}
return Json::encode($value);
}
if ($columnType && static::isNumericColumnType($columnType) && is_bool($value)) {
return (int)$value;
}
return $value;
}
/**
* Prepares a date to be sent to the database.
*
* @param mixed $date The date to be prepared
* @return string|null The prepped date, or `null` if it could not be prepared
*/
public static function prepareDateForDb(mixed $date): ?string
{
$date = DateTimeHelper::toDateTime($date);
if ($date === false) {
return null;
}
$date = clone $date;
$date->setTimezone(new DateTimeZone('UTC'));
return $date->format('Y-m-d H:i:s');
}
/**
* Prepares a money object to be sent to the database.
*
* @param mixed $money The money to be prepared
* @return string|null The prepped date, or `null` if it could not be prepared
* @since 4.0.0
*/
public static function prepareMoneyForDb(mixed $money): ?string
{
$money = MoneyHelper::toMoney($money);
if ($money === false) {
return null;
}
return $money->getAmount();
}
/**
* Prepares a value to be stored in a JSON column
*
* @param array $value The value to be stored as JSON
* @param Connection|null $db The database connection
* @return array|string
* @since 5.0.0
*/
public static function prepareForJsonColumn(array $value, ?Connection $db = null): array|string
{
if ($db === null) {
$db = self::db();
}
if ($db->getIsMaria()) {
return Json::encode($value);
}
return $value;
}
/**
* Returns the minimum number allowed for a given column type.
*
* @param string $columnType
* @return int|false The min allowed number, or false if it can't be determined
*/
public static function getMinAllowedValueForNumericColumn(string $columnType): int|false
{
$shortColumnType = self::parseColumnType($columnType);
if (isset(self::$_integerSizeRanges[$shortColumnType])) {
return self::$_integerSizeRanges[$shortColumnType][0];
}
// ¯\_(ツ)_/¯
return false;
}
/**
* Returns the maximum number allowed for a given column type.
*
* @param string $columnType
* @return int|false The max allowed number, or false if it can't be determined
*/
public static function getMaxAllowedValueForNumericColumn(string $columnType): int|false
{
$shortColumnType = self::parseColumnType($columnType);
if (isset(self::$_integerSizeRanges[$shortColumnType])) {
return self::$_integerSizeRanges[$shortColumnType][1];
}
// ¯\_(ツ)_/¯
return false;
}
/**
* Returns a number column type, taking the min, max, and number of decimal points into account.
*
* @param int|null $min
* @param int|null $max
* @param int|null $decimals
* @return string
* @throws Exception if no column types can contain this
*/
public static function getNumericalColumnType(?int $min = null, ?int $max = null, ?int $decimals = null): string
{
// Normalize the arguments
if (!is_numeric($min)) {
$min = self::$_integerSizeRanges[Schema::TYPE_INTEGER][0];
}
if (!is_numeric($max)) {
$max = self::$_integerSizeRanges[Schema::TYPE_INTEGER][1];
}
$decimals = is_numeric($decimals) && $decimals > 0 ? (int)$decimals : 0;
// Figure out the max length
$maxAbsSize = (int)max(abs($min), abs($max));
$length = ($maxAbsSize ? mb_strlen((string)$maxAbsSize) : 0) + $decimals;
// Decimal or int?
if ($decimals > 0) {
return Schema::TYPE_DECIMAL . "($length,$decimals)";
}
// Figure out the smallest possible int column type that will fit our min/max
foreach (self::$_integerSizeRanges as $type => [$typeMin, $typeMax]) {
if ($min >= $typeMin && $max <= $typeMax) {
return $type . "($length)";
}
}
throw new Exception("No integer column type can contain numbers between $min and $max");
}
/**
* Returns the maximum number of bytes a given textual column type can hold for a given database.
*
* @param string $columnType The textual column type to check
* @param Connection|null $db The database connection
* @return int|null|false The storage capacity of the column type in bytes, null if unlimited, or false if it can't be determined.
*/
public static function getTextualColumnStorageCapacity(string $columnType, ?Connection $db = null): int|null|false
{
if ($db === null) {
$db = self::db();
}
$shortColumnType = self::parseColumnType($columnType);
// CHAR and STRING depend on the defined length
if ($shortColumnType === Schema::TYPE_CHAR || $shortColumnType === Schema::TYPE_STRING) {
// Convert to the physical column type for the DB driver, to get the default length mixed in
$physicalColumnType = $db->getQueryBuilder()->getColumnType($columnType);
if (($length = self::parseColumnLength($physicalColumnType)) !== null) {
return $length;
}
// ¯\_(ツ)_/¯
return false;
}
if ($db->getIsMysql()) {
if (isset(self::$_mysqlTextSizes[$shortColumnType])) {
return self::$_mysqlTextSizes[$shortColumnType];
}
// ENUM depends on the options
if ($shortColumnType === MysqlSchema::TYPE_ENUM) {
return null;
}
// ¯\_(ツ)_/¯
return false;
}
// PostgreSQL doesn't impose a limit for text fields
if ($shortColumnType === Schema::TYPE_TEXT) {
// TEXT columns are variable-length in 'grez
return null;
}
// ¯\_(ツ)_/¯
return false;
}
/**
* Given a length of a piece of content, returns the underlying database column type to use for saving.
*
* @param int $contentLength
* @param Connection|null $db The database connection
* @return string
* @throws Exception if using an unsupported connection type
*/
public static function getTextualColumnTypeByContentLength(int $contentLength, ?Connection $db = null): string
{
if ($db === null) {
$db = self::db();
}
if ($db->getIsMysql()) {
// MySQL supports a bunch of non-standard text types
if ($contentLength <= self::$_mysqlTextSizes[MysqlSchema::TYPE_TINYTEXT]) {
return Schema::TYPE_STRING;
}
if ($contentLength <= self::$_mysqlTextSizes[Schema::TYPE_TEXT]) {
return Schema::TYPE_TEXT;
}
if ($contentLength <= self::$_mysqlTextSizes[MysqlSchema::TYPE_MEDIUMTEXT]) {
return MysqlSchema::TYPE_MEDIUMTEXT;
}
return MysqlSchema::TYPE_LONGTEXT;
}
return Schema::TYPE_TEXT;
}
/**
* Parses a column type definition and returns just the column type, if it can be determined.
*
* @param string $columnType
* @return string|null
*/
public static function parseColumnType(string $columnType): ?string
{
if (!preg_match('/^\w+/', $columnType, $matches)) {
return null;
}
return strtolower($matches[0]);
}
/**
* Parses a column type definition and returns just the column length/size.
*
* @param string $columnType
* @return int|null
*/
public static function parseColumnLength(string $columnType): ?int
{
if (!preg_match('/^\w+\((\d+)\)/', $columnType, $matches)) {
return null;
}
return (int)$matches[1];
}
/**
* Returns a simplified version of a given column type.
*
* @param string $columnType
* @return string
*/
public static function getSimplifiedColumnType(string $columnType): string
{
if (($shortColumnType = self::parseColumnType($columnType)) === null) {
return $columnType;
}
// Numeric?
if (in_array($shortColumnType, self::$_numericColumnTypes, true)) {
return self::SIMPLE_TYPE_NUMERIC;
}
// Textual?
if (in_array($shortColumnType, self::$_textualColumnTypes, true)) {
return self::SIMPLE_TYPE_TEXTUAL;
}
return $shortColumnType;
}
/**
* Returns whether two column type definitions are relatively compatible with each other.
*
* @param string $typeA
* @param string $typeB
* @return bool
*/
public static function areColumnTypesCompatible(string $typeA, string $typeB): bool
{
return static::getSimplifiedColumnType($typeA) === static::getSimplifiedColumnType($typeB);
}
/**
* Returns whether the given column type is numeric.
*
* @param string $columnType
* @return bool
*/
public static function isNumericColumnType(string $columnType): bool
{
return in_array(self::parseColumnType($columnType), self::$_numericColumnTypes, true);
}
/**
* Returns whether the given column type is textual.
*
* @param string $columnType
* @return bool
*/
public static function isTextualColumnType(string $columnType): bool
{
return in_array(self::parseColumnType($columnType), self::$_textualColumnTypes, true);
}
/**
* Escapes commas, asterisks, and colons in a string, so they are not treated as special characters in
* [[parseParam()]].
*
* @param string $value The param value.
* @return string The escaped param value.
*/
public static function escapeParam(string $value): string
{
if (in_array(strtolower($value), [':empty:', 'not :empty:', ':notempty:'])) {
return "\\$value";
}
$value = preg_replace('/(?<!\\\)[,*]/', '\\\$0', $value);
// If the value starts with an operator, escape that too.
foreach (self::$_operators as $operator) {
if (stripos($value, $operator) === 0) {
$value = "\\$value";
break;
}
}
return $value;
}
/**
* Unescapes commas, asterisks, and colons added to a string via [[escapeParam()]].
*
* @param string $value The param value.
* @return string The escaped param value.
* @since 4.4.0
*/
public static function unescapeParam(string $value): string
{
$value = preg_replace('/\\\([,*:])/', '$1', $value);
// If the value starts with an escaped operator, unescape that too.
foreach (self::$_operators as $operator) {
if (stripos($value, "\\$operator") === 0) {
$value = ltrim($value, '\\');
break;
}
}
return $value;
}
/**
* Escapes commas in a string so the value doesn’t get interpreted as an array by [[parseParam()]].
*
* @param string $value The param value.
* @return string The escaped param value.
* @since 4.0.0
*/
public static function escapeCommas(string $value): string
{
return preg_replace('/(?<!\\\),/', '\\\$0', $value);
}
/**
* Escapes underscores within a value for a `LIKE` condition.
*
* @param string $value The value
* @return string The escaped value
* @since 4.3.7
*/
public static function escapeForLike(string $value): string
{
return preg_replace('/(?<!\\\)_/', '\\_', $value);
}
/**
* Parses a query param value and returns a [[\yii\db\QueryInterface::where()]]-compatible condition.
*
* If the `$value` is a string, it will automatically be converted to an array, split on any commas within the
* string (via [[ArrayHelper::toArray()]]). If that is not desired behavior, you can escape the comma
* with a backslash before it.
*
* The first value can be set to either `and`, `or`, or `not` to define whether *all*, *any*, or *none* of the values must match.
* (`or` will be assumed by default.)
*
* Values can begin with the operators `'not '`, `'!='`, `'<='`, `'>='`, `'<'`, `'>'`, or `'='`. If they don’t,
* `'='` will be assumed.
*
* Values can also be set to either `':empty:'` or `':notempty:'` if you want to search for empty or non-empty
* database values. (An “empty” value is either `NULL` or an empty string of text).
*
* @param string $column The database column that the param is targeting.
* @param string|int|array $value The param value(s).
* @param string $defaultOperator The default operator to apply to the values
* (can be `not`, `!=`, `<=`, `>=`, `<`, `>`, or `=`)
* @param bool $caseInsensitive Whether the resulting condition should be case-insensitive
* @param string|null $columnType The database column type the param is targeting
* @return array|null
* @throws InvalidArgumentException if the param value isn’t compatible with the column type.
*/
public static function parseParam(
string $column,
mixed $value,
string $defaultOperator = '=',
bool $caseInsensitive = false,
string|null $columnType = null,
): ?array {
$param = QueryParam::parse($value);
if (empty($param->values)) {
return null;
}
$parsedColumnType = $columnType ? static::parseColumnType($columnType) : null;
if ($param->operator === QueryParam::NOT) {
$param->operator = QueryParam::AND;
$negate = true;
} else {
$negate = false;
}
$condition = [$param->operator];
$isMysql = self::db()->getIsMysql();
// Only PostgreSQL supports case-sensitive strings
if ($isMysql) {
$caseInsensitive = false;
}
$caseColumn = $caseInsensitive ? "lower([[$column]])" : $column;
$inVals = [];
$notInVals = [];
foreach ($param->values as $val) {
self::_normalizeEmptyValue($val);
$operator = self::_parseParamOperator($val, $defaultOperator, $negate);
if ($columnType !== null) {
if ($parsedColumnType === Schema::TYPE_BOOLEAN) {
// Convert val to a boolean
$val = ($val && $val !== ':empty:');
if ($operator === '!=') {
$val = !$val;
}
$condition[] = [$column => $val];
continue;
}
if (
static::isNumericColumnType($columnType) &&
$val !== ':empty:' &&
!is_numeric($val)
) {
throw new InvalidArgumentException("Invalid numeric value: $val");
}
}
if ($val === ':empty:') {
// If this is a textual column type, also check for empty strings
if (
($columnType === null && $isMysql) ||
($columnType !== null && static::isTextualColumnType($columnType))
) {
$valCondition = [
'or',
[$column => null],
[$column => ''],
];
} else {
$valCondition = [$column => null];
}
if ($operator === '!=') {
$valCondition = ['not', $valCondition];
}
$condition[] = $valCondition;
continue;
}
if (is_string($val)) {
// Trim any whitespace from the value
$val = trim($val);
// This could be a LIKE condition
if ($operator === '=' || $operator === '!=') {
$val = preg_replace('/^\*|(?<!\\\)\*$/', '%', $val, -1, $count);
$like = (bool)$count;
} else {
$like = false;
}
// Unescape any asterisks and :empty:/:notempty:
if (in_array(strtolower($val), ['\\:empty:', '\\:notempty:', '\\not :empty:'])) {
$val = ltrim($val, '\\');
} else {
$val = str_replace('\*', '*', $val);
}
if ($like) {
if ($caseInsensitive) {
$operator = $operator === '=' ? 'ilike' : 'not ilike';
} else {
$operator = $operator === '=' ? 'like' : 'not like';
}
$condition[] = [$operator, $column, static::escapeForLike($val), false];
continue;
}
if ($caseInsensitive) {
$val = mb_strtolower($val);
}
}
// ['or', 1, 2, 3] => IN (1, 2, 3)
if ($param->operator == QueryParam::OR && $operator === '=') {
$inVals[] = $val;
continue;
}
// ['and', '!=1', '!=2', '!=3'] => NOT IN (1, 2, 3)
if ($param->operator == QueryParam::AND && $operator === '!=') {
$notInVals[] = $val;
continue;
}
$condition[] = [$operator, $caseColumn, $val];
}
if (!empty($inVals)) {
$condition[] = self::_inCondition($caseColumn, $inVals);
}
if (!empty($notInVals)) {
$condition[] = ['not', self::_inCondition($caseColumn, $notInVals)];
}
// Skip the glue if there's only one condition
if (count($condition) === 2) {
return $condition[1];
}
return $condition;
}
/**
* Parses a query param value for a date/time column, and returns a
* [[\yii\db\QueryInterface::where()]]-compatible condition.
*
* @param string $column The database column that the param is targeting.
* @param string|array|DateTimeInterface $value The param value
* @param string $defaultOperator The default operator to apply to the values
* (can be `not`, `!=`, `<=`, `>=`, `<`, `>`, or `=`)
* @return array|null
*/
public static function parseDateParam(string $column, mixed $value, string $defaultOperator = '='): ?array
{
$param = QueryParam::parse($value);
if (empty($param->values)) {
return null;
}
$normalizedValues = [$param->operator];
foreach ($param->values as $val) {
// Is this an empty value?
self::_normalizeEmptyValue($val);
if ($val === ':empty:' || $val === 'not :empty:') {
$normalizedValues[] = $val;
// Sneak out early
continue;
}
$operator = self::_parseParamOperator($val, $defaultOperator);
// Assume that date params are set in the system timezone
$val = DateTimeHelper::toDateTime($val, true);
$normalizedValues[] = $operator . static::prepareDateForDb($val);
}
return static::parseParam($column, $normalizedValues, $defaultOperator, false, Schema::TYPE_DATETIME);
}
/**
* Parses a query param value for a money column, and returns a
* [[\yii\db\QueryInterface::where()]]-compatible condition.
*
* @param string $column The database column that the param is targeting.
* @param string $currency The currency code to use for the money object.
* @param string|array|Money $value The param value
* @param string $defaultOperator The default operator to apply to the values
* (can be `not`, `!=`, `<=`, `>=`, `<`, `>`, or `=`)
* @return array|null
* @since 4.0.0
*/
public static function parseMoneyParam(
string $column,
string $currency,
mixed $value,
string $defaultOperator = '=',
): ?array {
$param = QueryParam::parse($value);
if (empty($param->values)) {
return null;
}
$normalizedValues = [$param->operator];
foreach ($param->values as $val) {
// Is this an empty value?
self::_normalizeEmptyValue($val);
if ($val === ':empty:' || $val === 'not :empty:') {
$normalizedValues[] = $val;
// Sneak out early
continue;
}
$operator = self::_parseParamOperator($val, $defaultOperator);
// Assume that date params are set in the system timezone
$val = MoneyHelper::toMoney(['value' => $val, 'currency' => $currency]);
$normalizedValues[] = $operator . static::prepareMoneyForDb($val);
}
return static::parseParam($column, $normalizedValues, $defaultOperator, false, Schema::TYPE_DATETIME);
}
/**
* Parses a query param value for a boolean column and returns a
* [[\yii\db\QueryInterface::where()]]-compatible condition.
*
* The follow values are supported:
*
* - `true` or `false`
* - `:empty:` or `:notempty:` (normalizes to `false` and `true`)
* - `'not x'` or `'!= x'` (normalizes to the opposite of the boolean value of `x`)
* - Anything else (normalizes to the boolean value of itself)
*
* If `$defaultValue` is set, and it matches the normalized `$value`, then the resulting condition will match any
* `null` values as well.
*
* @param string $column The database column that the param is targeting.
* @param string|bool $value The param value
* @param bool|null $defaultValue How `null` values should be treated
* @param string $columnType The database column type the param is targeting
* @return array
* @since 3.4.14
*/
public static function parseBooleanParam(
string $column,
mixed $value,
?bool $defaultValue = null,
string $columnType = Schema::TYPE_BOOLEAN,
): array {
self::_normalizeEmptyValue($value);
$operator = self::_parseParamOperator($value, '=');
$value = $value && $value !== ':empty:';
if ($operator === '!=') {
$value = !$value;
}
if ($columnType === Schema::TYPE_JSON) {
$value = match ($value) {
true => 'true',
false => 'false',
};
$defaultValue = match ($defaultValue) {
true => 'true',
false => 'false',
null => null,
};
}
$condition = [$column => $value];
if ($defaultValue === $value) {
$condition = ['or', $condition, [$column => null]];
}
return $condition;
}
/**
* Parses a query param value for a numeric column and returns a
* [[\yii\db\QueryInterface::where()]]-compatible condition.
*
* The follow values are supported:
*
* - A number
* - `:empty:` or `:notempty:`
* - `'not x'` or `'!= x'`
* - `'> x'`, `'>= x'`, `'< x'`, or `'<= x'`, or a combination of those
*
* @param string $column The database column that the param is targeting.
* @param string|string[] $value The param value
* @param string $defaultOperator The default operator to apply to the values
* (can be `not`, `!=`, `<=`, `>=`, `<`, `>`, or `=`)
* @param string|null $columnType The database column type the param is targeting
* @return array|null
* @throws InvalidArgumentException if the param value isn’t numeric
* @since 4.0.0
*/
public static function parseNumericParam(
string $column,
mixed $value,
string $defaultOperator = '=',
string|null $columnType = Schema::TYPE_INTEGER,
): ?array {
return static::parseParam($column, $value, $defaultOperator, false, $columnType);
}
/**
* Normalizes a param value with a provided resolver function, unless the resolver function ever returns
* an empty value.
*
* If the original param value began with `and`, `or`, or `not`, that will be preserved.
*
* @param mixed $value The param value to be normalized
* @param callable $resolver Method to resolve non-model values to models
* @return bool Whether the value was normalized
* @since 3.7.40
*/
public static function normalizeParam(&$value, callable $resolver): bool
{
if ($value === null) {
return true;
}
if (!is_array($value)) {
$testValue = [$value];
if (static::normalizeParam($testValue, $resolver)) {
$value = $testValue;
return true;
}
return false;
}
$normalized = [];
foreach ($value as $item) {
if (
empty($normalized) &&
is_string($item) &&
in_array(strtolower($item), [QueryParam::OR, QueryParam::AND, QueryParam::NOT], true)
) {
$normalized[] = strtolower($item);
continue;
}
$item = $resolver($item);
if (!$item) {
// The value couldn't be normalized in full, so bail
return false;
}
$normalized[] = $item;
}
$value = $normalized;
return true;
}
/**
* Returns whether a given DB connection’s schema supports a column type.
*
* @param string $type
* @param Connection|null $db
* @return bool
* @throws NotSupportedException
*/
public static function isTypeSupported(string $type, ?Connection $db = null): bool
{
if ($db === null) {
$db = self::db();
}
/** @var MysqlSchema|PgsqlSchema $schema */
$schema = $db->getSchema();
return isset($schema->typeMap[$type]);
}
/**
* Creates and executes an `INSERT` SQL statement.
*
* The method will properly escape the column names, and bind the values to be inserted.
*
* If the table contains `dateCreated`, `dateUpdated`, and/or `uid` columns, those values will be included
* automatically, if not already set.
*
* @param string $table The table that new rows will be inserted into
* @param array $columns The column data (name=>value) to be inserted into the table
* @param Connection|null $db The database connection to use
* @return int The number of rows affected by the execution
* @throws DbException if execution failed
* @since 3.5.0
*/
public static function insert(string $table, array $columns, Connection|null $db = null): int
{
if ($db === null) {
$db = self::db();
}
return $db->createCommand()
->insert($table, $columns)
->execute();
}
/**
* Creates and executes a batch `INSERT` SQL statement.
*
* The method will properly escape the column names, and bind the values to be inserted.
*
* If the table contains `dateCreated`, `dateUpdated`, and/or `uid` columns, those values will be included
* automatically, if not already set.
*
* @param string $table The table that new rows will be inserted into
* @param array $columns The column names
* @param array $rows The rows to be batch inserted into the table
* @param Connection|null $db The database connection to use
* @return int The number of rows affected by the execution
* @throws DbException if execution failed
* @since 3.5.0
*/
public static function batchInsert(string $table, array $columns, array $rows, Connection|null $db = null): int
{
if ($db === null) {
$db = self::db();
}
return $db->createCommand()
->batchInsert($table, $columns, $rows)
->execute();
}