/
Validator.php
610 lines (559 loc) · 19.2 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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 2.2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Validation;
use ArrayAccess;
use Cake\Validation\RulesProvider;
use Cake\Validation\ValidationSet;
use Cake\Utility\Hash;
use Countable;
use IteratorAggregate;
/**
* 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 http://book.cakephp.org/3.0/en/core-libraries/validation.html
*/
class Validator implements ArrayAccess, IteratorAggregate, Countable
{
/**
* Holds the ValidationSet objects array
*
* @var array
*/
protected $_fields = [];
/**
* An associative array of objects or classes containing methods
* used for validation
*
* @var array
*/
protected $_providers = [];
/**
* 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 = [];
/**
* Constructor
*
*/
public function __construct()
{
$this->_useI18n = function_exists('__d');
}
/**
* Returns an array of fields that have failed validation. On the current model. This method will
* actually run validation rules over data, not just return the 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 invalid fields
*/
public function errors(array $data, $newRecord = true)
{
$errors = [];
$requiredMessage = 'This field is required';
$emptyMessage = 'This field cannot be left empty';
if ($this->_useI18n) {
$requiredMessage = __d('cake', 'This field is required');
$emptyMessage = __d('cake', 'This field cannot be left empty');
}
$flat = Hash::flatten($data);
foreach ($this->_fields as $name => $field) {
$isPath = strpos($name, '.') !== false;
$keyPresent = array_key_exists($name, $isPath ? $flat : $data);
if (!$keyPresent && !$this->_checkPresence($field, $newRecord)) {
$errors[$name]['_required'] = isset($this->_presenceMessages[$name])
? $this->_presenceMessages[$name]
: $requiredMessage;
continue;
}
if (!$keyPresent) {
continue;
}
$value = $isPath ? $flat[$name] : $data[$name];
$providers = $this->_providers;
$context = compact('data', 'newRecord', 'field', 'providers');
$canBeEmpty = $this->_canBeEmpty($field, $context);
$isEmpty = $this->_fieldIsEmpty($value);
if (!$canBeEmpty && $isEmpty) {
$errors[$name]['_empty'] = isset($this->_allowEmptyMessages[$name])
? $this->_allowEmptyMessages[$name]
: $emptyMessage;
continue;
}
if ($isEmpty) {
continue;
}
$result = $this->_processRules($name, $value, $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($name, ValidationSet $set = null)
{
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($name)
{
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.
*
* If called with no arguments, it will return the provider stored under that name if
* it exists, otherwise it returns this instance of chaining.
*
* @param string $name The name under which the provider should be set.
* @param null|object|string $object Provider object or class name.
* @return $this|object|string|null
*/
public function provider($name, $object = null)
{
if ($object === null) {
if (isset($this->_providers[$name])) {
return $this->_providers[$name];
}
if ($name === 'default') {
return $this->_providers[$name] = new RulesProvider;
}
return null;
}
$this->_providers[$name] = $object;
return $this;
}
/**
* 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)
{
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)
{
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)
{
if (!$rules instanceof ValidationSet) {
$set = new ValidationSet;
foreach ((array)$rules as $name => $rule) {
$set->add($name, $rule);
}
}
$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)
{
unset($this->_fields[$field]);
}
/**
* Returns an iterator for each of the fields to be validated
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->_fields);
}
/**
* Returns the number of fields having validation rules
*
* @return int
*/
public function count()
{
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' => 'notEmpty'])
* ->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 removed
* @param array|string $name The alias for a single rule or multiple rules array
* @param array|\Cake\Validation\ValidationRule $rule the rule to add
* @return $this
*/
public function add($field, $name, $rule = [])
{
$field = $this->field($field);
if (!is_array($name)) {
$rules = [$name => $rule];
} else {
$rules = $name;
}
foreach ($rules as $name => $rule) {
$field->add($name, $rule);
}
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($field, $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.
*
* @param string $field the name of the field
* @param bool|string $mode Valid values are true, false, 'create', 'update'
* @param string|null $message The message to show if the field presence validation fails.
* @return $this
*/
public function requirePresence($field, $mode = true, $message = null)
{
$this->field($field)->isPresenceRequired($mode);
if ($message) {
$this->_presenceMessages[$field] = $message;
}
return $this;
}
/**
* Allows a field to be empty.
*
* 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:
*
* ```
* $validator->allowEmpty('email'); // Email can be empty
* $validator->allowEmpty('email', 'create'); // Email can be empty on create
* $validator->allowEmpty('email', 'update'); // Email can be empty on 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.
*
* @param string $field the name of the field
* @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.
* @return $this
*/
public function allowEmpty($field, $when = true)
{
$this->field($field)->isEmptyAllowed($when);
return $this;
}
/**
* Sets a field to require a non-empty value.
*
* This is the opposite of allowEmpty() which allows a field to be empty.
* By using $mode equal to 'create' or 'update', you can make fields required
* when records are first created, or when they are updated.
*
* ### Example:
*
* ```
* $message = 'This field cannot be empty';
* $validator->notEmpty('email'); // Email cannot be empty
* $validator->notEmpty('email', $message, 'create'); // Email can be empty on update
* $validator->notEmpty('email', $message, 'update'); // Email can be empty on create
* ```
*
* It is possible to conditionally disallow emptiness on a field by passing a callback
* as the third argument. The callback will receive the validation context array as
* argument:
*
* ```
* $validator->notEmpty('email', 'Email is required', function ($context) {
* return $context['newRecord'] && $context['data']['role'] !== 'admin';
* });
* ```
*
* Because this and `allowEmpty()` modify the same internal state, the last
* method called will take precedence.
*
* @param string $field the name of the field
* @param string $message The validation message to show if the field is not
* @param bool|string|callable $when Indicates when the field is not allowed
* to be empty. Valid values are true (always), 'create', 'update'. If a
* callable is passed then the field will allowed be empty only when
* the callback returns false.
* @return $this
*/
public function notEmpty($field, $message = null, $when = false)
{
if ($when === 'create' || $when === 'update') {
$when = $when === 'create' ? 'update' : 'create';
} elseif (is_callable($when)) {
$when = function ($context) use ($when) {
return !$when($context);
};
}
$this->field($field)->isEmptyAllowed($when);
if ($message) {
$this->_allowEmptyMessages[$field] = $message;
}
return $this;
}
/**
* Returns whether or not a field can be left empty for a new or already existing
* record.
*
* @param string $field Field name.
* @param bool $newRecord whether the data to be validated is new or to be updated.
* @return bool
*/
public function isEmptyAllowed($field, $newRecord)
{
$providers = $this->_providers;
$data = [];
$context = compact('data', 'newRecord', 'field', 'providers');
return $this->_canBeEmpty($this->field($field), $context);
}
/**
* Returns whether or not a field can be left out for a new or already existing
* record.
*
* @param string $field Field name.
* @param bool $newRecord whether the data to be validated is new or to be updated.
* @return bool
*/
public function isPresenceRequired($field, $newRecord)
{
return !$this->_checkPresence($this->field($field), $newRecord);
}
/**
* Returns false if any validation for the passed rule set should be stopped
* due to the field missing in the data array
*
* @param ValidationSet $field the set of rules for a field
* @param bool $newRecord whether the data to be validated is new or to be updated.
* @return bool
*/
protected function _checkPresence($field, $newRecord)
{
$required = $field->isPresenceRequired();
if (in_array($required, ['create', 'update'], true)) {
return (
($required === 'create' && !$newRecord) ||
($required === 'update' && $newRecord)
);
}
return !$required;
}
/**
* Returns whether the field can be left blank according to `allowEmpty`
*
* @param ValidationSet $field the set of rules for a field
* @param array $context a key value list of data containing the validation context.
* @return bool
*/
protected function _canBeEmpty($field, $context)
{
$allowed = $field->isEmptyAllowed();
if (!is_string($allowed) && is_callable($allowed)) {
return $allowed($context);
}
$newRecord = $context['newRecord'];
if (in_array($allowed, ['create', 'update'], true)) {
$allowed = (
($allowed === 'create' && $newRecord) ||
($allowed === 'update' && !$newRecord)
);
}
return $allowed;
}
/**
* Returns true if the field is empty in the passed data array
*
* @param mixed $data value to check against
* @return bool
*/
protected function _fieldIsEmpty($data)
{
if (empty($data) && $data !== '0' && $data !== false && $data !== 0 && $data !== 0.0) {
return true;
}
$isArray = is_array($data);
if ($isArray && (isset($data['year']) || isset($data['hour']))) {
$value = implode('', $data);
return strlen($value) === 0;
}
if ($isArray && isset($data['name'], $data['type'], $data['tmp_name'], $data['error'])) {
return (int)$data['error'] === UPLOAD_ERR_NO_FILE;
}
return false;
}
/**
* Iterates over each rule in the validation set and collects the errors resulting
* from executing them
*
* @param string $field The name of the field that is being processed
* @param ValidationSet $rules the list of rules for a field
* @param mixed $value The field value.
* @param array $data the full data passed to the validator
* @param bool $newRecord whether is it a new record or an existing one
* @return array
*/
protected function _processRules($field, $value, ValidationSet $rules, $data, $newRecord)
{
$errors = [];
// Loading default provider in case there is none
$this->provider('default');
$message = 'The provided value is invalid';
if ($this->_useI18n) {
$message = __d('cake', 'The provided value is invalid');
}
foreach ($rules as $name => $rule) {
$result = $rule->process($value, $this->_providers, compact('newRecord', 'data', 'field'));
if ($result === true) {
continue;
}
$errors[$name] = $message;
if (is_string($result)) {
$errors[$name] = $result;
}
if ($rule->isLast()) {
break;
}
}
return $errors;
}
/**
* Get the printable version of this object.
*
* @return array
*/
public function __debugInfo()
{
$fields = [];
foreach ($this->_fields as $name => $fieldSet) {
$fields[$name] = [
'isPresenceRequired' => $fieldSet->isPresenceRequired(),
'isEmptyAllowed' => $fieldSet->isEmptyAllowed(),
'rules' => array_keys($fieldSet->rules()),
];
}
return [
'_presenceMessages' => $this->_presenceMessages,
'_allowEmptyMessages' => $this->_allowEmptyMessages,
'_useI18n' => $this->_useI18n,
'_providers' => array_keys($this->_providers),
'_fields' => $fields
];
}
}