-
Notifications
You must be signed in to change notification settings - Fork 12
/
Validation.php
1805 lines (1625 loc) · 60 KB
/
Validation.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
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 1.2.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Validation;
use Cake\I18n\Time;
use Cake\Utility\Text;
use Countable;
use DateTimeInterface;
use InvalidArgumentException;
use LogicException;
use NumberFormatter;
use Psr\Http\Message\UploadedFileInterface;
use RuntimeException;
/**
* Validation Class. Used for validation of model data
*
* Offers different validation methods.
*/
class Validation
{
/**
* Default locale
*
* @var string
*/
public const DEFAULT_LOCALE = 'en_US';
/**
* Same as operator.
*
* @var string
*/
public const COMPARE_SAME = '===';
/**
* Not same as comparison operator.
*
* @var string
*/
public const COMPARE_NOT_SAME = '!==';
/**
* Equal to comparison operator.
*
* @var string
*/
public const COMPARE_EQUAL = '==';
/**
* Not equal to comparison operator.
*
* @var string
*/
public const COMPARE_NOT_EQUAL = '!=';
/**
* Greater than comparison operator.
*
* @var string
*/
public const COMPARE_GREATER = '>';
/**
* Greater than or equal to comparison operator.
*
* @var string
*/
public const COMPARE_GREATER_OR_EQUAL = '>=';
/**
* Less than comparison operator.
*
* @var string
*/
public const COMPARE_LESS = '<';
/**
* Less than or equal to comparison operator.
*
* @var string
*/
public const COMPARE_LESS_OR_EQUAL = '<=';
/**
* @var string[]
*/
protected const COMPARE_STRING = [
self::COMPARE_EQUAL,
self::COMPARE_NOT_EQUAL,
self::COMPARE_SAME,
self::COMPARE_NOT_SAME,
];
/**
* Datetime ISO8601 format
*
* @var string
*/
public const DATETIME_ISO8601 = 'iso8601';
/**
* Some complex patterns needed in multiple places
*
* @var array
*/
protected static $_pattern = [
'hostname' => '(?:[_\p{L}0-9][-_\p{L}0-9]*\.)*(?:[\p{L}0-9][-\p{L}0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,})',
'latitude' => '[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)',
'longitude' => '[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)',
];
/**
* Holds an array of errors messages set in this class.
* These are used for debugging purposes
*
* @var array
*/
public static $errors = [];
/**
* Checks that a string contains something other than whitespace
*
* Returns true if string contains something other than whitespace
*
* @param mixed $check Value to check
* @return bool Success
*/
public static function notBlank($check): bool
{
if (empty($check) && !is_bool($check) && !is_numeric($check)) {
return false;
}
return static::_check($check, '/[^\s]+/m');
}
/**
* Checks that a string contains only integer or letters.
*
* This method's definition of letters and integers includes unicode characters.
* Use `asciiAlphaNumeric()` if you want to exclude unicode.
*
* @param mixed $check Value to check
* @return bool Success
*/
public static function alphaNumeric($check): bool
{
if ((empty($check) && $check !== '0') || !is_scalar($check)) {
return false;
}
return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
}
/**
* Checks that a doesn't contain any alpha numeric characters
*
* This method's definition of letters and integers includes unicode characters.
* Use `notAsciiAlphaNumeric()` if you want to exclude ascii only.
*
* @param mixed $check Value to check
* @return bool Success
*/
public static function notAlphaNumeric($check): bool
{
return !static::alphaNumeric($check);
}
/**
* Checks that a string contains only ascii integer or letters.
*
* @param mixed $check Value to check
* @return bool Success
*/
public static function asciiAlphaNumeric($check): bool
{
if ((empty($check) && $check !== '0') || !is_scalar($check)) {
return false;
}
return self::_check($check, '/^[[:alnum:]]+$/');
}
/**
* Checks that a doesn't contain any non-ascii alpha numeric characters
*
* @param mixed $check Value to check
* @return bool Success
*/
public static function notAsciiAlphaNumeric($check): bool
{
return !static::asciiAlphaNumeric($check);
}
/**
* Checks that a string length is within specified range.
* Spaces are included in the character count.
* Returns true if string matches value min, max, or between min and max,
*
* @param mixed $check Value to check for length
* @param int $min Minimum value in range (inclusive)
* @param int $max Maximum value in range (inclusive)
* @return bool Success
*/
public static function lengthBetween($check, int $min, int $max): bool
{
if (!is_scalar($check)) {
return false;
}
$length = mb_strlen((string)$check);
return $length >= $min && $length <= $max;
}
/**
* Validation of credit card numbers.
* Returns true if $check is in the proper credit card format.
*
* @param mixed $check credit card number to validate
* @param string|string[] $type 'all' may be passed as a string, defaults to fast which checks format of
* most major credit cards if an array is used only the values of the array are checked.
* Example: ['amex', 'bankcard', 'maestro']
* @param bool $deep set to true this will check the Luhn algorithm of the credit card.
* @param string|null $regex A custom regex, this will be used instead of the defined regex values.
* @return bool Success
* @see \Cake\Validation\Validation::luhn()
*/
public static function creditCard($check, $type = 'fast', bool $deep = false, ?string $regex = null): bool
{
if (!(is_string($check) || is_int($check))) {
return false;
}
$check = str_replace(['-', ' '], '', (string)$check);
if (mb_strlen($check) < 13) {
return false;
}
if ($regex !== null && static::_check($check, $regex)) {
return !$deep || static::luhn($check);
}
$cards = [
'all' => [
'amex' => '/^3[47]\\d{13}$/',
'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
'disc' => '/^(?:6011|650\\d)\\d{12}$/',
'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
'enroute' => '/^2(?:014|149)\\d{11}$/',
'jcb' => '/^(3\\d{4}|2131|1800)\\d{11}$/',
'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
'mc' => '/^(5[1-5]\\d{14})|(2(?:22[1-9]|2[3-9][0-9]|[3-6][0-9]{2}|7[0-1][0-9]|720)\\d{12})$/',
'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
// phpcs:ignore Generic.Files.LineLength
'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
'visa' => '/^4\\d{12}(\\d{3})?$/',
'voyager' => '/^8699[0-9]{11}$/',
],
// phpcs:ignore Generic.Files.LineLength
'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/',
];
if (is_array($type)) {
foreach ($type as $value) {
$regex = $cards['all'][strtolower($value)];
if (static::_check($check, $regex)) {
return static::luhn($check);
}
}
} elseif ($type === 'all') {
foreach ($cards['all'] as $value) {
$regex = $value;
if (static::_check($check, $regex)) {
return static::luhn($check);
}
}
} else {
$regex = $cards['fast'];
if (static::_check($check, $regex)) {
return static::luhn($check);
}
}
return false;
}
/**
* Used to check the count of a given value of type array or Countable.
*
* @param mixed $check The value to check the count on.
* @param string $operator Can be either a word or operand
* is greater >, is less <, greater or equal >=
* less or equal <=, is less <, equal to ==, not equal !=
* @param int $expectedCount The expected count value.
* @return bool Success
*/
public static function numElements($check, string $operator, int $expectedCount): bool
{
if (!is_array($check) && !$check instanceof Countable) {
return false;
}
return self::comparison(count($check), $operator, $expectedCount);
}
/**
* Used to compare 2 numeric values.
*
* @param string|int $check1 The left value to compare.
* @param string $operator Can be one of following operator strings:
* '>', '<', '>=', '<=', '==', '!=', '===' and '!=='. You can use one of
* the Validation::COMPARE_* constants.
* @param string|int $check2 The right value to compare.
* @return bool Success
*/
public static function comparison($check1, string $operator, $check2): bool
{
if (
(!is_numeric($check1) || !is_numeric($check2)) &&
!in_array($operator, static::COMPARE_STRING)
) {
return false;
}
switch ($operator) {
case static::COMPARE_GREATER:
if ($check1 > $check2) {
return true;
}
break;
case static::COMPARE_LESS:
if ($check1 < $check2) {
return true;
}
break;
case static::COMPARE_GREATER_OR_EQUAL:
if ($check1 >= $check2) {
return true;
}
break;
case static::COMPARE_LESS_OR_EQUAL:
if ($check1 <= $check2) {
return true;
}
break;
case static::COMPARE_EQUAL:
if ($check1 == $check2) {
return true;
}
break;
case static::COMPARE_NOT_EQUAL:
if ($check1 != $check2) {
return true;
}
break;
case static::COMPARE_SAME:
if ($check1 === $check2) {
return true;
}
break;
case static::COMPARE_NOT_SAME:
if ($check1 !== $check2) {
return true;
}
break;
default:
static::$errors[] = 'You must define a valid $operator parameter for Validation::comparison()';
}
return false;
}
/**
* Compare one field to another.
*
* If both fields have exactly the same value this method will return true.
*
* @param mixed $check The value to find in $field.
* @param string $field The field to check $check against. This field must be present in $context.
* @param array $context The validation context.
* @return bool
*/
public static function compareWith($check, string $field, array $context): bool
{
return self::compareFields($check, $field, static::COMPARE_SAME, $context);
}
/**
* Compare one field to another.
*
* Return true if the comparison matches the expected result.
*
* @param mixed $check The value to find in $field.
* @param string $field The field to check $check against. This field must be present in $context.
* @param string $operator Comparison operator. See Validation::comparison().
* @param array $context The validation context.
* @return bool
* @since 3.6.0
*/
public static function compareFields($check, string $field, string $operator, array $context): bool
{
if (!isset($context['data']) || !array_key_exists($field, $context['data'])) {
return false;
}
return static::comparison($check, $operator, $context['data'][$field]);
}
/**
* Checks if a string contains one or more non-alphanumeric characters.
*
* Returns true if string contains at least the specified number of non-alphanumeric characters
*
* @param mixed $check Value to check
* @param int $count Number of non-alphanumerics to check for
* @return bool Success
* @deprecated 4.0.0 Use {@link notAlphaNumeric()} instead. Will be removed in 5.0
*/
public static function containsNonAlphaNumeric($check, int $count = 1): bool
{
deprecationWarning('Validation::containsNonAlphaNumeric() is deprecated. Use notAlphaNumeric() instead.');
if (!is_string($check)) {
return false;
}
$matches = preg_match_all('/[^a-zA-Z0-9]/', $check);
return $matches >= $count;
}
/**
* Used when a custom regular expression is needed.
*
* @param mixed $check The value to check.
* @param string|null $regex If $check is passed as a string, $regex must also be set to valid regular expression
* @return bool Success
*/
public static function custom($check, ?string $regex = null): bool
{
if (!is_scalar($check)) {
return false;
}
if ($regex === null) {
static::$errors[] = 'You must define a regular expression for Validation::custom()';
return false;
}
return static::_check($check, $regex);
}
/**
* Date validation, determines if the string passed is a valid date.
* keys that expect full month, day and year will validate leap years.
*
* Years are valid from 0001 to 2999.
*
* ### Formats:
*
* - `dmy` 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
* - `mdy` 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
* - `ymd` 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
* - `dMy` 27 December 2006 or 27 Dec 2006
* - `Mdy` December 27, 2006 or Dec 27, 2006 comma is optional
* - `My` December 2006 or Dec 2006
* - `my` 12/2006 or 12/06 separators can be a space, period, dash, forward slash
* - `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash
* - `y` 2006 just the year without any separators
*
* @param mixed $check a valid date string/object
* @param string|array $format Use a string or an array of the keys above.
* Arrays should be passed as ['dmy', 'mdy', etc]
* @param string|null $regex If a custom regular expression is used this is the only validation that will occur.
* @return bool Success
*/
public static function date($check, $format = 'ymd', ?string $regex = null): bool
{
if ($check instanceof DateTimeInterface) {
return true;
}
if (is_object($check)) {
return false;
}
if (is_array($check)) {
$check = static::_getDateString($check);
$format = 'ymd';
}
if ($regex !== null) {
return static::_check($check, $regex);
}
$month = '(0[123456789]|10|11|12)';
$separator = '([- /.])';
// Don't allow 0000, but 0001-2999 are ok.
$fourDigitYear = '(?:(?!0000)[012]\d{3})';
$twoDigitYear = '(?:\d{2})';
$year = '(?:' . $fourDigitYear . '|' . $twoDigitYear . ')';
// phpcs:disable Generic.Files.LineLength
// 2 or 4 digit leap year sub-pattern
$leapYear = '(?:(?:(?:(?!0000)[012]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))';
// 4 digit leap year sub-pattern
$fourDigitLeapYear = '(?:(?:(?:(?!0000)[012]\\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))';
$regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
$separator . '(?:0?[13-9]|1[0-2])\\2))' . $year . '$|^(?:29' .
$separator . '0?2\\3' . $leapYear . ')$|^(?:0?[1-9]|1\\d|2[0-8])' .
$separator . '(?:(?:0?[1-9])|(?:1[0-2]))\\4' . $year . '$%';
$regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])' .
$separator . '(?:29|30)\\2))' . $year . '$|^(?:0?2' . $separator . '29\\3' . $leapYear . ')$|^(?:(?:0?[1-9])|(?:1[0-2]))' .
$separator . '(?:0?[1-9]|1\\d|2[0-8])\\4' . $year . '$%';
$regex['ymd'] = '%^(?:(?:' . $leapYear .
$separator . '(?:0?2\\1(?:29)))|(?:' . $year .
$separator . '(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[13-9]|1[0-2])\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]))))$%';
$regex['dMy'] = '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ ' . $fourDigitLeapYear . '))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ' . $fourDigitYear . '$/';
$regex['Mdy'] = '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep)(tember)?|(Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ' . $fourDigitLeapYear . ')))))\\,?\\ ' . $fourDigitYear . ')$/';
$regex['My'] = '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)' .
$separator . $fourDigitYear . '$%';
// phpcs:enable Generic.Files.LineLength
$regex['my'] = '%^(' . $month . $separator . $year . ')$%';
$regex['ym'] = '%^(' . $year . $separator . $month . ')$%';
$regex['y'] = '%^(' . $fourDigitYear . ')$%';
$format = is_array($format) ? array_values($format) : [$format];
foreach ($format as $key) {
if (static::_check($check, $regex[$key]) === true) {
return true;
}
}
return false;
}
/**
* Validates a datetime value
*
* All values matching the "date" core validation rule, and the "time" one will be valid
*
* @param mixed $check Value to check
* @param string|array $dateFormat Format of the date part. See Validation::date() for more information.
* Or `Validation::DATETIME_ISO8601` to validate an ISO8601 datetime value.
* @param string|null $regex Regex for the date part. If a custom regular expression is used
* this is the only validation that will occur.
* @return bool True if the value is valid, false otherwise
* @see \Cake\Validation\Validation::date()
* @see \Cake\Validation\Validation::time()
*/
public static function datetime($check, $dateFormat = 'ymd', ?string $regex = null): bool
{
if ($check instanceof DateTimeInterface) {
return true;
}
if (is_object($check)) {
return false;
}
if (is_array($dateFormat) && count($dateFormat) === 1) {
$dateFormat = reset($dateFormat);
}
if ($dateFormat === static::DATETIME_ISO8601 && !static::iso8601($check)) {
return false;
}
$valid = false;
if (is_array($check)) {
$check = static::_getDateString($check);
$dateFormat = 'ymd';
}
$parts = preg_split('/[\sT]+/', $check);
if (!empty($parts) && count($parts) > 1) {
$date = rtrim(array_shift($parts), ',');
$time = implode(' ', $parts);
if ($dateFormat === static::DATETIME_ISO8601) {
$dateFormat = 'ymd';
$time = preg_split("/[TZ\-\+\.]/", $time);
$time = array_shift($time);
}
$valid = static::date($date, $dateFormat, $regex) && static::time($time);
}
return $valid;
}
/**
* Validates an iso8601 datetime format
* ISO8601 recognize datetime like 2019 as a valid date. To validate and check date integrity, use @see \Cake\Validation\Validation::datetime()
*
* @param mixed $check Value to check
* @return bool True if the value is valid, false otherwise
* @see Regex credits: https://www.myintervals.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/
*/
public static function iso8601($check): bool
{
if ($check instanceof DateTimeInterface) {
return true;
}
if (is_object($check)) {
return false;
}
// phpcs:ignore Generic.Files.LineLength
$regex = '/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/';
return static::_check($check, $regex);
}
/**
* Time validation, determines if the string passed is a valid time.
* Validates time as 24hr (HH:MM[:SS][.FFFFFF]) or am/pm ([H]H:MM[a|p]m)
*
* Seconds and fractional seconds (microseconds) are allowed but optional
* in 24hr format.
*
* @param mixed $check a valid time string/object
* @return bool Success
*/
public static function time($check): bool
{
if ($check instanceof DateTimeInterface) {
return true;
}
if (is_array($check)) {
$check = static::_getDateString($check);
}
if (!is_scalar($check)) {
return false;
}
$meridianClockRegex = '^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$';
$standardClockRegex = '^([01]\d|2[0-3])((:[0-5]\d){1,2}|(:[0-5]\d){2}\.\d{0,6})$';
return static::_check($check, '%' . $meridianClockRegex . '|' . $standardClockRegex . '%');
}
/**
* Date and/or time string validation.
* Uses `I18n::Time` to parse the date. This means parsing is locale dependent.
*
* @param mixed $check a date string or object (will always pass)
* @param string $type Parser type, one out of 'date', 'time', and 'datetime'
* @param string|int|null $format any format accepted by IntlDateFormatter
* @return bool Success
* @throws \InvalidArgumentException when unsupported $type given
* @see \Cake\I18n\Time::parseDate()
* @see \Cake\I18n\Time::parseTime()
* @see \Cake\I18n\Time::parseDateTime()
*/
public static function localizedTime($check, string $type = 'datetime', $format = null): bool
{
if ($check instanceof DateTimeInterface) {
return true;
}
if (!is_string($check)) {
return false;
}
static $methods = [
'date' => 'parseDate',
'time' => 'parseTime',
'datetime' => 'parseDateTime',
];
if (empty($methods[$type])) {
throw new InvalidArgumentException('Unsupported parser type given.');
}
$method = $methods[$type];
return Time::$method($check, $format) !== null;
}
/**
* Validates if passed value is boolean-like.
*
* The list of what is considered to be boolean values, may be set via $booleanValues.
*
* @param bool|int|string $check Value to check.
* @param array $booleanValues List of valid boolean values, defaults to `[true, false, 0, 1, '0', '1']`.
* @return bool Success.
*/
public static function boolean($check, array $booleanValues = []): bool
{
if (!$booleanValues) {
$booleanValues = [true, false, 0, 1, '0', '1'];
}
return in_array($check, $booleanValues, true);
}
/**
* Validates if given value is truthy.
*
* The list of what is considered to be truthy values, may be set via $truthyValues.
*
* @param bool|int|string $check Value to check.
* @param array $truthyValues List of valid truthy values, defaults to `[true, 1, '1']`.
* @return bool Success.
*/
public static function truthy($check, array $truthyValues = []): bool
{
if (!$truthyValues) {
$truthyValues = [true, 1, '1'];
}
return in_array($check, $truthyValues, true);
}
/**
* Validates if given value is falsey.
*
* The list of what is considered to be falsey values, may be set via $falseyValues.
*
* @param bool|int|string $check Value to check.
* @param array $falseyValues List of valid falsey values, defaults to `[false, 0, '0']`.
* @return bool Success.
*/
public static function falsey($check, array $falseyValues = []): bool
{
if (!$falseyValues) {
$falseyValues = [false, 0, '0'];
}
return in_array($check, $falseyValues, true);
}
/**
* Checks that a value is a valid decimal. Both the sign and exponent are optional.
*
* Valid Places:
*
* - null => Any number of decimal places, including none. The '.' is not required.
* - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
* - 1..N => Exactly that many number of decimal places. The '.' is required.
*
* @param mixed $check The value the test for decimal.
* @param int|true|null $places Decimal places.
* @param string|null $regex If a custom regular expression is used, this is the only validation that will occur.
* @return bool Success
*/
public static function decimal($check, $places = null, ?string $regex = null): bool
{
if (!is_scalar($check)) {
return false;
}
if ($regex === null) {
$lnum = '[0-9]+';
$dnum = "[0-9]*[\.]{$lnum}";
$sign = '[+-]?';
$exp = "(?:[eE]{$sign}{$lnum})?";
if ($places === null) {
$regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
} elseif ($places === true) {
if (is_float($check) && floor($check) === $check) {
$check = sprintf('%.1f', $check);
}
$regex = "/^{$sign}{$dnum}{$exp}$/";
} elseif (is_numeric($places)) {
$places = '[0-9]{' . $places . '}';
$dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
$regex = "/^{$sign}{$dnum}{$exp}$/";
} else {
return false;
}
}
// account for localized floats.
$locale = ini_get('intl.default_locale') ?: static::DEFAULT_LOCALE;
$formatter = new NumberFormatter($locale, NumberFormatter::DECIMAL);
$decimalPoint = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
$groupingSep = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
// There are two types of non-breaking spaces - we inject a space to account for human input
if ($groupingSep == "\xc2\xa0" || $groupingSep == "\xe2\x80\xaf") {
$check = str_replace([' ', $groupingSep, $decimalPoint], ['', '', '.'], (string)$check);
} else {
$check = str_replace([$groupingSep, $decimalPoint], ['', '.'], (string)$check);
}
return static::_check($check, $regex);
}
/**
* Validates for an email address.
*
* Only uses getmxrr() checking for deep validation, or
* any PHP version on a non-windows distribution
*
* @param mixed $check Value to check
* @param bool $deep Perform a deeper validation (if true), by also checking availability of host
* @param string|null $regex Regex to use (if none it will use built in regex)
* @return bool Success
*/
public static function email($check, ?bool $deep = false, ?string $regex = null): bool
{
if (!is_string($check)) {
return false;
}
if ($regex === null) {
// phpcs:ignore Generic.Files.LineLength
$regex = '/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/ui';
}
$return = static::_check($check, $regex);
if ($deep === false || $deep === null) {
return $return;
}
if ($return === true && preg_match('/@(' . static::$_pattern['hostname'] . ')$/i', $check, $regs)) {
if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
return true;
}
if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
return true;
}
return is_array(gethostbynamel($regs[1] . '.'));
}
return false;
}
/**
* Checks that value is exactly $comparedTo.
*
* @param mixed $check Value to check
* @param mixed $comparedTo Value to compare
* @return bool Success
*/
public static function equalTo($check, $comparedTo): bool
{
return $check === $comparedTo;
}
/**
* Checks that value has a valid file extension.
*
* @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check
* @param string[] $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
* @return bool Success
*/
public static function extension($check, array $extensions = ['gif', 'jpeg', 'png', 'jpg']): bool
{
if ($check instanceof UploadedFileInterface) {
$check = $check->getClientFilename();
} elseif (is_array($check) && isset($check['name'])) {
$check = $check['name'];
} elseif (is_array($check)) {
return static::extension(array_shift($check), $extensions);
}
if (empty($check)) {
return false;
}
$extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
foreach ($extensions as $value) {
if ($extension === strtolower($value)) {
return true;
}
}
return false;
}
/**
* Validation of an IP address.
*
* @param mixed $check The string to test.
* @param string $type The IP Protocol version to validate against
* @return bool Success
*/
public static function ip($check, string $type = 'both'): bool
{
if (!is_string($check)) {
return false;
}
$type = strtolower($type);
$flags = 0;
if ($type === 'ipv4') {
$flags = FILTER_FLAG_IPV4;
}
if ($type === 'ipv6') {
$flags = FILTER_FLAG_IPV6;
}
return (bool)filter_var($check, FILTER_VALIDATE_IP, ['flags' => $flags]);
}
/**
* Checks whether the length of a string (in characters) is greater or equal to a minimal length.
*
* @param mixed $check The string to test
* @param int $min The minimal string length
* @return bool Success
*/
public static function minLength($check, int $min): bool
{
if (!is_scalar($check)) {
return false;
}
return mb_strlen((string)$check) >= $min;
}
/**
* Checks whether the length of a string (in characters) is smaller or equal to a maximal length.
*
* @param mixed $check The string to test
* @param int $max The maximal string length
* @return bool Success
*/
public static function maxLength($check, int $max): bool
{
if (!is_scalar($check)) {
return false;
}
return mb_strlen((string)$check) <= $max;
}
/**
* Checks whether the length of a string (in bytes) is greater or equal to a minimal length.
*
* @param mixed $check The string to test
* @param int $min The minimal string length (in bytes)
* @return bool Success
*/
public static function minLengthBytes($check, int $min): bool
{
if (!is_scalar($check)) {
return false;
}
return strlen((string)$check) >= $min;
}
/**
* Checks whether the length of a string (in bytes) is smaller or equal to a maximal length.
*
* @param mixed $check The string to test
* @param int $max The maximal string length
* @return bool Success
*/
public static function maxLengthBytes($check, int $max): bool
{
if (!is_scalar($check)) {
return false;
}
return strlen((string)$check) <= $max;
}
/**
* Checks that a value is a monetary amount.
*
* @param mixed $check Value to check
* @param string $symbolPosition Where symbol is located (left/right)
* @return bool Success
*/
public static function money($check, string $symbolPosition = 'left'): bool
{
$money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
if ($symbolPosition === 'right') {
$regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
} else {
$regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
}
return static::_check($check, $regex);
}
/**
* Validates a multiple select. Comparison is case sensitive by default.
*
* Valid Options
*