-
Notifications
You must be signed in to change notification settings - Fork 12
/
Validator.php
2750 lines (2479 loc) · 100 KB
/
Validator.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 2.2.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Validation;
use ArrayAccess;
use ArrayIterator;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use Psr\Http\Message\UploadedFileInterface;
use Traversable;
/**
* Validator object encapsulates all methods related to data validations for a model
* It also provides an API to dynamically change validation rules for each model field.
*
* Implements ArrayAccess to easily modify rules in the set
*
* @link https://book.cakephp.org/4/en/core-libraries/validation.html
*/
class Validator implements ArrayAccess, IteratorAggregate, Countable
{
/**
* By using 'create' you can make fields required when records are first created.
*
* @var string
*/
public const WHEN_CREATE = 'create';
/**
* By using 'update', you can make fields required when they are updated.
*
* @var string
*/
public const WHEN_UPDATE = 'update';
/**
* Used to flag nested rules created with addNested() and addNestedMany()
*
* @var string
*/
public const NESTED = '_nested';
/**
* A flag for allowEmptyFor()
*
* When `null` is given, it will be recognized as empty.
*
* @var int
*/
public const EMPTY_NULL = 0;
/**
* A flag for allowEmptyFor()
*
* When an empty string is given, it will be recognized as empty.
*
* @var int
*/
public const EMPTY_STRING = 1;
/**
* A flag for allowEmptyFor()
*
* When an empty array is given, it will be recognized as empty.
*
* @var int
*/
public const EMPTY_ARRAY = 2;
/**
* A flag for allowEmptyFor()
*
* When an array is given, if it has at least the `name`, `type`, `tmp_name` and `error` keys,
* and the value of `error` is equal to `UPLOAD_ERR_NO_FILE`, the value will be recognized as
* empty.
*
* When an instance of \Psr\Http\Message\UploadedFileInterface is given the
* return value of it's getError() method must be equal to `UPLOAD_ERR_NO_FILE`.
*
* @var int
*/
public const EMPTY_FILE = 4;
/**
* A flag for allowEmptyFor()
*
* When an array is given, if it contains the `year` key, and only empty strings
* or null values, it will be recognized as empty.
*
* @var int
*/
public const EMPTY_DATE = 8;
/**
* A flag for allowEmptyFor()
*
* When an array is given, if it contains the `hour` key, and only empty strings
* or null values, it will be recognized as empty.
*
* @var int
*/
public const EMPTY_TIME = 16;
/**
* A combination of the all EMPTY_* flags
*
* @var int
*/
public const EMPTY_ALL = self::EMPTY_STRING
| self::EMPTY_ARRAY
| self::EMPTY_FILE
| self::EMPTY_DATE
| self::EMPTY_TIME;
/**
* Holds the ValidationSet objects array
*
* @var \Cake\Validation\ValidationSet[]
* @psalm-var array<string, \Cake\Validation\ValidationSet>
*/
protected $_fields = [];
/**
* An associative array of objects or classes containing methods
* used for validation
*
* @var array
*/
protected $_providers = [];
/**
* An associative array of objects or classes used as a default provider list
*
* @var array
*/
protected static $_defaultProviders = [];
/**
* Contains the validation messages associated with checking the presence
* for each corresponding field.
*
* @var array
*/
protected $_presenceMessages = [];
/**
* Whether or not to use I18n functions for translating default error messages
*
* @var bool
*/
protected $_useI18n = false;
/**
* Contains the validation messages associated with checking the emptiness
* for each corresponding field.
*
* @var array
*/
protected $_allowEmptyMessages = [];
/**
* Contains the flags which specify what is empty for each corresponding field.
*
* @var array
*/
protected $_allowEmptyFlags = [];
/**
* Whether to apply last flag to generated rule(s).
*
* @var bool
*/
protected $_stopOnFailure = false;
/**
* Constructor
*/
public function __construct()
{
$this->_useI18n = function_exists('__d');
$this->_providers = self::$_defaultProviders;
}
/**
* Whether to stop validation rule evaluation on the first failed rule.
*
* When enabled the first failing rule per field will cause validation to stop.
* When disabled all rules will be run even if there are failures.
*
* @param bool $stopOnFailure If to apply last flag.
* @return $this
*/
public function setStopOnFailure(bool $stopOnFailure = true)
{
$this->_stopOnFailure = $stopOnFailure;
return $this;
}
/**
* Validates and returns an array of failed fields and their error messages.
*
* @param array $data The data to be checked for errors
* @param bool $newRecord whether the data to be validated is new or to be updated.
* @return array[] Array of failed fields
* @deprecated 3.9.0 Renamed to {@link validate()}.
*/
public function errors(array $data, bool $newRecord = true): array
{
deprecationWarning('`Validator::errors()` is deprecated. Use `Validator::validate()` instead.');
return $this->validate($data, $newRecord);
}
/**
* Validates and returns an array of failed fields and their error messages.
*
* @param array $data The data to be checked for errors
* @param bool $newRecord whether the data to be validated is new or to be updated.
* @return array[] Array of failed fields
*/
public function validate(array $data, bool $newRecord = true): array
{
$errors = [];
foreach ($this->_fields as $name => $field) {
$keyPresent = array_key_exists($name, $data);
$providers = $this->_providers;
$context = compact('data', 'newRecord', 'field', 'providers');
if (!$keyPresent && !$this->_checkPresence($field, $context)) {
$errors[$name]['_required'] = $this->getRequiredMessage($name);
continue;
}
if (!$keyPresent) {
continue;
}
$canBeEmpty = $this->_canBeEmpty($field, $context);
$flags = static::EMPTY_NULL;
if (isset($this->_allowEmptyFlags[$name])) {
$flags = $this->_allowEmptyFlags[$name];
}
$isEmpty = $this->isEmpty($data[$name], $flags);
if (!$canBeEmpty && $isEmpty) {
$errors[$name]['_empty'] = $this->getNotEmptyMessage($name);
continue;
}
if ($isEmpty) {
continue;
}
$result = $this->_processRules($name, $field, $data, $newRecord);
if ($result) {
$errors[$name] = $result;
}
}
return $errors;
}
/**
* Returns a ValidationSet object containing all validation rules for a field, if
* passed a ValidationSet as second argument, it will replace any other rule set defined
* before
*
* @param string $name [optional] The fieldname to fetch.
* @param \Cake\Validation\ValidationSet|null $set The set of rules for field
* @return \Cake\Validation\ValidationSet
*/
public function field(string $name, ?ValidationSet $set = null): ValidationSet
{
if (empty($this->_fields[$name])) {
$set = $set ?: new ValidationSet();
$this->_fields[$name] = $set;
}
return $this->_fields[$name];
}
/**
* Check whether or not a validator contains any rules for the given field.
*
* @param string $name The field name to check.
* @return bool
*/
public function hasField(string $name): bool
{
return isset($this->_fields[$name]);
}
/**
* Associates an object to a name so it can be used as a provider. Providers are
* objects or class names that can contain methods used during validation of for
* deciding whether a validation rule can be applied. All validation methods,
* when called will receive the full list of providers stored in this validator.
*
* @param string $name The name under which the provider should be set.
* @param object|string $object Provider object or class name.
* @return $this
*/
public function setProvider(string $name, $object)
{
$this->_providers[$name] = $object;
return $this;
}
/**
* Returns the provider stored under that name if it exists.
*
* @param string $name The name under which the provider should be set.
* @return object|string|null
*/
public function getProvider(string $name)
{
if (isset($this->_providers[$name])) {
return $this->_providers[$name];
}
if ($name !== 'default') {
return null;
}
$this->_providers[$name] = new RulesProvider();
return $this->_providers[$name];
}
/**
* Returns the default provider stored under that name if it exists.
*
* @param string $name The name under which the provider should be retrieved.
* @return object|string|null
*/
public static function getDefaultProvider(string $name)
{
if (!isset(self::$_defaultProviders[$name])) {
return null;
}
return self::$_defaultProviders[$name];
}
/**
* Associates an object to a name so it can be used as a default provider.
*
* @param string $name The name under which the provider should be set.
* @param object|string $object Provider object or class name.
* @return void
*/
public static function addDefaultProvider(string $name, $object): void
{
self::$_defaultProviders[$name] = $object;
}
/**
* Get the list of default providers.
*
* @return string[]
*/
public static function getDefaultProviders(): array
{
return array_keys(self::$_defaultProviders);
}
/**
* Get the list of providers in this validator.
*
* @return string[]
*/
public function providers(): array
{
return array_keys($this->_providers);
}
/**
* Returns whether a rule set is defined for a field or not
*
* @param string $field name of the field to check
* @return bool
*/
public function offsetExists($field): bool
{
return isset($this->_fields[$field]);
}
/**
* Returns the rule set for a field
*
* @param string $field name of the field to check
* @return \Cake\Validation\ValidationSet
*/
public function offsetGet($field): ValidationSet
{
return $this->field($field);
}
/**
* Sets the rule set for a field
*
* @param string $field name of the field to set
* @param array|\Cake\Validation\ValidationSet $rules set of rules to apply to field
* @return void
*/
public function offsetSet($field, $rules): void
{
if (!$rules instanceof ValidationSet) {
$set = new ValidationSet();
foreach ($rules as $name => $rule) {
$set->add($name, $rule);
}
$rules = $set;
}
$this->_fields[$field] = $rules;
}
/**
* Unsets the rule set for a field
*
* @param string $field name of the field to unset
* @return void
*/
public function offsetUnset($field): void
{
unset($this->_fields[$field]);
}
/**
* Returns an iterator for each of the fields to be validated
*
* @return \Cake\Validation\ValidationSet[]
* @psalm-return \Traversable<string, \Cake\Validation\ValidationSet>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->_fields);
}
/**
* Returns the number of fields having validation rules
*
* @return int
*/
public function count(): int
{
return count($this->_fields);
}
/**
* Adds a new rule to a field's rule set. If second argument is an array
* then rules list for the field will be replaced with second argument and
* third argument will be ignored.
*
* ### Example:
*
* ```
* $validator
* ->add('title', 'required', ['rule' => 'notBlank'])
* ->add('user_id', 'valid', ['rule' => 'numeric', 'message' => 'Invalid User'])
*
* $validator->add('password', [
* 'size' => ['rule' => ['lengthBetween', 8, 20]],
* 'hasSpecialCharacter' => ['rule' => 'validateSpecialchar', 'message' => 'not valid']
* ]);
* ```
*
* @param string $field The name of the field from which the rule will be added
* @param array|string $name The alias for a single rule or multiple rules array
* @param array|\Cake\Validation\ValidationRule $rule the rule to add
* @throws \InvalidArgumentException If numeric index cannot be resolved to a string one
* @return $this
*/
public function add(string $field, $name, $rule = [])
{
$validationSet = $this->field($field);
if (!is_array($name)) {
$rules = [$name => $rule];
} else {
$rules = $name;
}
foreach ($rules as $name => $rule) {
if (is_array($rule)) {
$rule += [
'rule' => $name,
'last' => $this->_stopOnFailure,
];
}
if (!is_string($name)) {
/** @psalm-suppress PossiblyUndefinedMethod */
$name = $rule['rule'];
if (is_array($name)) {
$name = array_shift($name);
}
if ($validationSet->offsetExists($name)) {
$message = 'You cannot add a rule without a unique name, already existing rule found: ' . $name;
throw new InvalidArgumentException($message);
}
deprecationWarning(
'Adding validation rules without a name key is deprecated. Update rules array to have string keys.'
);
}
$validationSet->add($name, $rule);
}
return $this;
}
/**
* Adds a nested validator.
*
* Nesting validators allows you to define validators for array
* types. For example, nested validators are ideal when you want to validate a
* sub-document, or complex array type.
*
* This method assumes that the sub-document has a 1:1 relationship with the parent.
*
* The providers of the parent validator will be synced into the nested validator, when
* errors are checked. This ensures that any validation rule providers connected
* in the parent will have the same values in the nested validator when rules are evaluated.
*
* @param string $field The root field for the nested validator.
* @param \Cake\Validation\Validator $validator The nested validator.
* @param string|null $message The error message when the rule fails.
* @param string|callable|null $when Either 'create' or 'update' or a callable that returns
* true when the validation rule should be applied.
* @return $this
*/
public function addNested(string $field, Validator $validator, ?string $message = null, $when = null)
{
$extra = array_filter(['message' => $message, 'on' => $when]);
$validationSet = $this->field($field);
$validationSet->add(static::NESTED, $extra + ['rule' => function ($value, $context) use ($validator, $message) {
if (!is_array($value)) {
return false;
}
foreach ($this->providers() as $provider) {
/** @psalm-suppress PossiblyNullArgument */
$validator->setProvider($provider, $this->getProvider($provider));
}
$errors = $validator->validate($value, $context['newRecord']);
$message = $message ? [static::NESTED => $message] : [];
return empty($errors) ? true : $errors + $message;
}]);
return $this;
}
/**
* Adds a nested validator.
*
* Nesting validators allows you to define validators for array
* types. For example, nested validators are ideal when you want to validate many
* similar sub-documents or complex array types.
*
* This method assumes that the sub-document has a 1:N relationship with the parent.
*
* The providers of the parent validator will be synced into the nested validator, when
* errors are checked. This ensures that any validation rule providers connected
* in the parent will have the same values in the nested validator when rules are evaluated.
*
* @param string $field The root field for the nested validator.
* @param \Cake\Validation\Validator $validator The nested validator.
* @param string|null $message The error message when the rule fails.
* @param string|callable|null $when Either 'create' or 'update' or a callable that returns
* true when the validation rule should be applied.
* @return $this
*/
public function addNestedMany(string $field, Validator $validator, ?string $message = null, $when = null)
{
$extra = array_filter(['message' => $message, 'on' => $when]);
$validationSet = $this->field($field);
$validationSet->add(static::NESTED, $extra + ['rule' => function ($value, $context) use ($validator, $message) {
if (!is_array($value)) {
return false;
}
foreach ($this->providers() as $provider) {
/** @psalm-suppress PossiblyNullArgument */
$validator->setProvider($provider, $this->getProvider($provider));
}
$errors = [];
foreach ($value as $i => $row) {
if (!is_array($row)) {
return false;
}
$check = $validator->validate($row, $context['newRecord']);
if (!empty($check)) {
$errors[$i] = $check;
}
}
$message = $message ? [static::NESTED => $message] : [];
return empty($errors) ? true : $errors + $message;
}]);
return $this;
}
/**
* Removes a rule from the set by its name
*
* ### Example:
*
* ```
* $validator
* ->remove('title', 'required')
* ->remove('user_id')
* ```
*
* @param string $field The name of the field from which the rule will be removed
* @param string|null $rule the name of the rule to be removed
* @return $this
*/
public function remove(string $field, ?string $rule = null)
{
if ($rule === null) {
unset($this->_fields[$field]);
} else {
$this->field($field)->remove($rule);
}
return $this;
}
/**
* Sets whether a field is required to be present in data array.
* You can also pass array. Using an array will let you provide the following
* keys:
*
* - `mode` individual mode for field
* - `message` individual error message for field
*
* You can also set mode and message for all passed fields, the individual
* setting takes precedence over group settings.
*
* @param string|array $field the name of the field or list of fields.
* @param bool|string|callable $mode Valid values are true, false, 'create', 'update'.
* If a callable is passed then the field will be required only when the callback
* returns true.
* @param string|null $message The message to show if the field presence validation fails.
* @return $this
*/
public function requirePresence($field, $mode = true, ?string $message = null)
{
$defaults = [
'mode' => $mode,
'message' => $message,
];
if (!is_array($field)) {
$field = $this->_convertValidatorToArray($field, $defaults);
}
foreach ($field as $fieldName => $setting) {
$settings = $this->_convertValidatorToArray($fieldName, $defaults, $setting);
$fieldName = current(array_keys($settings));
$this->field($fieldName)->requirePresence($settings[$fieldName]['mode']);
if ($settings[$fieldName]['message']) {
$this->_presenceMessages[$fieldName] = $settings[$fieldName]['message'];
}
}
return $this;
}
/**
* Allows a field to be empty. You can also pass array.
* Using an array will let you provide the following keys:
*
* - `when` individual when condition for field
* - 'message' individual message for field
*
* You can also set when and message for all passed fields, the individual setting
* takes precedence over group settings.
*
* This is the opposite of notEmpty() which requires a field to not be empty.
* By using $mode equal to 'create' or 'update', you can allow fields to be empty
* when records are first created, or when they are updated.
*
* ### Example:
*
* ```
* // Email can be empty
* $validator->allowEmpty('email');
*
* // Email can be empty on create
* $validator->allowEmpty('email', Validator::WHEN_CREATE);
*
* // Email can be empty on update
* $validator->allowEmpty('email', Validator::WHEN_UPDATE);
*
* // Email and subject can be empty on update
* $validator->allowEmpty(['email', 'subject'], Validator::WHEN_UPDATE;
*
* // Email can be always empty, subject and content can be empty on update.
* $validator->allowEmpty(
* [
* 'email' => [
* 'when' => true
* ],
* 'content' => [
* 'message' => 'Content cannot be empty'
* ],
* 'subject'
* ],
* Validator::WHEN_UPDATE
* );
* ```
*
* It is possible to conditionally allow emptiness on a field by passing a callback
* as a second argument. The callback will receive the validation context array as
* argument:
*
* ```
* $validator->allowEmpty('email', function ($context) {
* return !$context['newRecord'] || $context['data']['role'] === 'admin';
* });
* ```
*
* This method will correctly detect empty file uploads and date/time/datetime fields.
*
* Because this and `notEmpty()` modify the same internal state, the last
* method called will take precedence.
*
* @deprecated 3.7.0 Use {@link allowEmptyString()}, {@link allowEmptyArray()}, {@link allowEmptyFile()},
* {@link allowEmptyDate()}, {@link allowEmptyTime()}, {@link allowEmptyDateTime()} or {@link allowEmptyFor()} instead.
* @param string|array $field the name of the field or a list of fields
* @param bool|string|callable $when Indicates when the field is allowed to be empty
* Valid values are true (always), 'create', 'update'. If a callable is passed then
* the field will allowed to be empty only when the callback returns true.
* @param string|null $message The message to show if the field is not
* @return $this
*/
public function allowEmpty($field, $when = true, $message = null)
{
deprecationWarning(
'allowEmpty() is deprecated. '
. 'Use allowEmptyString(), allowEmptyArray(), allowEmptyFile(), allowEmptyDate(), allowEmptyTime(), '
. 'allowEmptyDateTime() or allowEmptyFor() instead.'
);
$defaults = [
'when' => $when,
'message' => $message,
];
if (!is_array($field)) {
$field = $this->_convertValidatorToArray($field, $defaults);
}
foreach ($field as $fieldName => $setting) {
$settings = $this->_convertValidatorToArray($fieldName, $defaults, $setting);
$fieldName = array_keys($settings)[0];
$this->allowEmptyFor(
$fieldName,
static::EMPTY_ALL,
$settings[$fieldName]['when'],
$settings[$fieldName]['message']
);
}
return $this;
}
/**
* Low-level method to indicate that a field can be empty.
*
* This method should generally not be used and instead you should
* use:
*
* - `allowEmptyString()`
* - `allowEmptyArray()`
* - `allowEmptyFile()`
* - `allowEmptyDate()`
* - `allowEmptyDatetime()`
* - `allowEmptyTime()`
*
* Should be used as their APIs are simpler to operate and read.
*
* You can also set flags, when and message for all passed fields, the individual
* setting takes precedence over group settings.
*
* ### Example:
*
* ```
* // Email can be empty
* $validator->allowEmptyFor('email', Validator::EMPTY_STRING);
*
* // Email can be empty on create
* $validator->allowEmptyFor('email', Validator::EMPTY_STRING, Validator::WHEN_CREATE);
*
* // Email can be empty on update
* $validator->allowEmptyFor('email', Validator::EMPTY_STRING, Validator::WHEN_UPDATE);
* ```
*
* It is possible to conditionally allow emptiness on a field by passing a callback
* as a second argument. The callback will receive the validation context array as
* argument:
*
* ```
* $validator->allowEmpty('email', Validator::EMPTY_STRING, function ($context) {
* return !$context['newRecord'] || $context['data']['role'] === 'admin';
* });
* ```
*
* If you want to allow other kind of empty data on a field, you need to pass other
* flags:
*
* ```
* $validator->allowEmptyFor('photo', Validator::EMPTY_FILE);
* $validator->allowEmptyFor('published', Validator::EMPTY_STRING | Validator::EMPTY_DATE | Validator::EMPTY_TIME);
* $validator->allowEmptyFor('items', Validator::EMPTY_STRING | Validator::EMPTY_ARRAY);
* ```
*
* You can also use convenience wrappers of this method. The following calls are the
* same as above:
*
* ```
* $validator->allowEmptyFile('photo');
* $validator->allowEmptyDateTime('published');
* $validator->allowEmptyArray('items');
* ```
*
* @param string $field The name of the field.
* @param int|null $flags A bitmask of EMPTY_* flags which specify what is empty.
* If no flags/bitmask is provided only `null` will be allowed as empty value.
* @param bool|string|callable $when Indicates when the field is allowed to be empty
* Valid values are true, false, 'create', 'update'. If a callable is passed then
* the field will allowed to be empty only when the callback returns true.
* @param string|null $message The message to show if the field is not
* @since 3.7.0
* @return $this
*/
public function allowEmptyFor(string $field, ?int $flags = null, $when = true, ?string $message = null)
{
$this->field($field)->allowEmpty($when);
if ($message) {
$this->_allowEmptyMessages[$field] = $message;
}
if ($flags !== null) {
$this->_allowEmptyFlags[$field] = $flags;
}
return $this;
}
/**
* Allows a field to be an empty string.
*
* This method is equivalent to calling allowEmptyFor() with EMPTY_STRING flag.
*
* @param string $field The name of the field.
* @param string|null $message The message to show if the field is not
* @param bool|string|callable $when Indicates when the field is allowed to be empty
* Valid values are true, false, 'create', 'update'. If a callable is passed then
* the field will allowed to be empty only when the callback returns true.
* @return $this
* @see \Cake\Validation\Validator::allowEmptyFor() For detail usage
*/
public function allowEmptyString(string $field, ?string $message = null, $when = true)
{
return $this->allowEmptyFor($field, self::EMPTY_STRING, $when, $message);
}
/**
* Requires a field to be not be an empty string.
*
* Opposite to allowEmptyString()
*
* @param string $field The name of the field.
* @param string|null $message The message to show if the field is empty.
* @param bool|string|callable $when Indicates when the field is not allowed
* to be empty. Valid values are false (never), 'create', 'update'. If a
* callable is passed then the field will be required to be not empty when
* the callback returns true.
* @return $this
* @see \Cake\Validation\Validator::allowEmptyString()
* @since 3.8.0
*/
public function notEmptyString(string $field, ?string $message = null, $when = false)
{
$when = $this->invertWhenClause($when);
return $this->allowEmptyFor($field, self::EMPTY_STRING, $when, $message);
}
/**
* Allows a field to be an empty array.
*
* This method is equivalent to calling allowEmptyFor() with EMPTY_STRING +
* EMPTY_ARRAY flags.
*
* @param string $field The name of the field.
* @param string|null $message The message to show if the field is not
* @param bool|string|callable $when Indicates when the field is allowed to be empty
* Valid values are true, false, 'create', 'update'. If a callable is passed then
* the field will allowed to be empty only when the callback returns true.
* @return $this
* @since 3.7.0
* @see \Cake\Validation\Validator::allowEmptyFor() for examples.
*/
public function allowEmptyArray(string $field, ?string $message = null, $when = true)
{
return $this->allowEmptyFor($field, self::EMPTY_STRING | self::EMPTY_ARRAY, $when, $message);
}
/**
* Require a field to be a non-empty array
*
* Opposite to allowEmptyArray()
*
* @param string $field The name of the field.
* @param string|null $message The message to show if the field is empty.
* @param bool|string|callable $when Indicates when the field is not allowed
* to be empty. Valid values are false (never), 'create', 'update'. If a
* callable is passed then the field will be required to be not empty when
* the callback returns true.
* @return $this
* @see \Cake\Validation\Validator::allowEmptyArray()
*/
public function notEmptyArray(string $field, ?string $message = null, $when = false)
{
$when = $this->invertWhenClause($when);
return $this->allowEmptyFor($field, self::EMPTY_STRING | self::EMPTY_ARRAY, $when, $message);
}
/**
* Allows a field to be an empty file.
*
* This method is equivalent to calling allowEmptyFor() with EMPTY_FILE flag.
* File fields will not accept `''`, or `[]` as empty values. Only `null` and a file
* upload with `error` equal to `UPLOAD_ERR_NO_FILE` will be treated as empty.
*
* @param string $field The name of the field.
* @param string|null $message The message to show if the field is not
* @param bool|string|callable $when Indicates when the field is allowed to be empty
* Valid values are true, 'create', 'update'. If a callable is passed then
* the field will allowed to be empty only when the callback returns true.
* @return $this
* @since 3.7.0
* @see \Cake\Validation\Validator::allowEmptyFor() For detail usage
*/
public function allowEmptyFile(string $field, ?string $message = null, $when = true)
{
return $this->allowEmptyFor($field, self::EMPTY_FILE, $when, $message);
}
/**
* Require a field to be a not-empty file.
*
* Opposite to allowEmptyFile()
*
* @param string $field The name of the field.
* @param string|null $message The message to show if the field is empty.
* @param bool|string|callable $when Indicates when the field is not allowed
* to be empty. Valid values are false (never), 'create', 'update'. If a
* callable is passed then the field will be required to be not empty when
* the callback returns true.
* @return $this
* @since 3.8.0
* @see \Cake\Validation\Validator::allowEmptyFile()
*/
public function notEmptyFile(string $field, ?string $message = null, $when = false)
{
$when = $this->invertWhenClause($when);
return $this->allowEmptyFor($field, self::EMPTY_FILE, $when, $message);
}
/**