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
|
<?php
/**
* ModelValidator.
*
* Provides the Model validation logic.
*
* PHP versions 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Model
* @since CakePHP(tm) v 2.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeValidationSet', 'Model/Validator');
/**
* ModelValidator 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 as usually done with `Model::$validate`
* definition array
*
* @package Cake.Model
* @link http://book.cakephp.org/2.0/en/data-validation.html
*/
class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
/**
* Holds the CakeValidationSet objects array
*
* @var array
*/
protected $_fields = array();
/**
* Holds the reference to the model this Validator is attached to
*
* @var Model
*/
protected $_model = array();
/**
* The validators $validate property, used for checking wheter validation
* rules definition changed in the model and should be refreshed in this class
*
* @var array
*/
protected $_validate = array();
/**
* Holds the available custom callback methods, usually taken from model methods
* and behavior methods
*
* @var array
*/
protected $_methods = array();
/**
* Constructor
*
* @param Model $Model A reference to the Model the Validator is attached to
*/
public function __construct(Model $Model) {
$this->_model = $Model;
}
/**
* Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
* that use the 'with' key as well. Since `Model::_saveMulti` is incapable of exiting a save operation.
*
* Will validate the currently set data. Use `Model::set()` or `Model::create()` to set the active data.
*
* @param array $options An optional array of custom options to be made available in the beforeValidate callback
* @return boolean True if there are no errors
*/
public function validates($options = array()) {
$errors = $this->errors($options);
if (empty($errors) && $errors !== false) {
$errors = $this->_validateWithModels($options);
}
if (is_array($errors)) {
return count($errors) === 0;
}
return $errors;
}
/**
* Validates a single record, as well as all its directly associated records.
*
* #### Options
*
* - atomic: If true (default), returns boolean. If false returns array.
* - fieldList: Equivalent to the $fieldList parameter in Model::save()
* - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
*
* Warning: This method could potentially change the passed argument `$data`,
* If you do not want this to happen, make a copy of `$data` before passing it
* to this method
*
* @param array $data Record data to validate. This should be an array indexed by association name.
* @param array $options Options to use when validating record data (see above), See also $options of validates().
* @return array|boolean If atomic: True on success, or false on failure.
* Otherwise: array similar to the $data array passed, but values are set to true/false
* depending on whether each record validated successfully.
*/
public function validateAssociated(&$data, $options = array()) {
$model = $this->getModel();
$options = array_merge(array('atomic' => true, 'deep' => false), $options);
$model->validationErrors = $validationErrors = $return = array();
$model->create(null);
if (!($model->set($data) && $model->validates($options))) {
$validationErrors[$model->alias] = $model->validationErrors;
$return[$model->alias] = false;
} else {
$return[$model->alias] = true;
}
$data = $model->data;
if (!empty($options['deep']) && isset($data[$model->alias])) {
$recordData = $data[$model->alias];
unset($data[$model->alias]);
$data = array_merge($data, $recordData);
}
$associations = $model->getAssociated();
foreach ($data as $association => &$values) {
$validates = true;
if (isset($associations[$association])) {
if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
if ($options['deep']) {
$validates = $model->{$association}->validateAssociated($values, $options);
} else {
$model->{$association}->create(null);
$validates = $model->{$association}->set($values) && $model->{$association}->validates($options);
$data[$association] = $model->{$association}->data[$model->{$association}->alias];
}
if (is_array($validates)) {
if (in_array(false, $validates, true)) {
$validates = false;
} else {
$validates = true;
}
}
$return[$association] = $validates;
} elseif ($associations[$association] === 'hasMany') {
$validates = $model->{$association}->validateMany($values, $options);
$return[$association] = $validates;
}
if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
$validationErrors[$association] = $model->{$association}->validationErrors;
}
}
}
$model->validationErrors = $validationErrors;
if (isset($validationErrors[$model->alias])) {
$model->validationErrors = $validationErrors[$model->alias];
unset($validationErrors[$model->alias]);
$model->validationErrors = array_merge($model->validationErrors, $validationErrors);
}
if (!$options['atomic']) {
return $return;
}
if ($return[$model->alias] === false || !empty($model->validationErrors)) {
return false;
}
return true;
}
/**
* Validates multiple individual records for a single model
*
* #### Options
*
* - atomic: If true (default), returns boolean. If false returns array.
* - fieldList: Equivalent to the $fieldList parameter in Model::save()
* - deep: If set to true, all associated data will be validated as well.
*
* Warning: This method could potentially change the passed argument `$data`,
* If you do not want this to happen, make a copy of `$data` before passing it
* to this method
*
* @param array $data Record data to validate. This should be a numerically-indexed array
* @param array $options Options to use when validating record data (see above), See also $options of validates().
* @return boolean True on success, or false on failure.
* @return mixed If atomic: True on success, or false on failure.
* Otherwise: array similar to the $data array passed, but values are set to true/false
* depending on whether each record validated successfully.
*/
public function validateMany(&$data, $options = array()) {
$model = $this->getModel();
$options = array_merge(array('atomic' => true, 'deep' => false), $options);
$model->validationErrors = $validationErrors = $return = array();
foreach ($data as $key => &$record) {
if ($options['deep']) {
$validates = $model->validateAssociated($record, $options);
} else {
$model->create(null);
$validates = $model->set($record) && $model->validates($options);
$data[$key] = $model->data;
}
if ($validates === false || (is_array($validates) && in_array(false, $validates, true))) {
$validationErrors[$key] = $model->validationErrors;
$validates = false;
} else {
$validates = true;
}
$return[$key] = $validates;
}
$model->validationErrors = $validationErrors;
if (!$options['atomic']) {
return $return;
}
if (empty($model->validationErrors)) {
return true;
}
return false;
}
/**
* 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 string $options An optional array of custom options to be made available in the beforeValidate callback
* @return array Array of invalid fields
* @see ModelValidator::validates()
*/
public function errors($options = array()) {
if (!$this->_triggerBeforeValidate($options)) {
return false;
}
$model = $this->getModel();
if (!$this->_parseRules()) {
return $model->validationErrors;
}
$fieldList = isset($options['fieldList']) ? $options['fieldList'] : array();
$exists = $model->exists();
$methods = $this->getMethods();
$fields = $this->_validationList($fieldList);
foreach ($fields as $field) {
$field->setMethods($methods);
$field->setValidationDomain($model->validationDomain);
$data = isset($model->data[$model->alias]) ? $model->data[$model->alias] : array();
$errors = $field->validate($data, $exists);
foreach ($errors as $error) {
$this->invalidate($field->field, $error);
}
}
$model->getEventManager()->dispatch(new CakeEvent('Model.afterValidate', $model));
return $model->validationErrors;
}
/**
* Marks a field as invalid, optionally setting a message explaining
* why the rule failed
*
* @param string $field The name of the field to invalidate
* @param string $message Validation message explaining why the rule failed, defaults to true.
* @return void
*/
public function invalidate($field, $message = true) {
$this->getModel()->validationErrors[$field][] = $message;
}
/**
* Gets all possible custom methods from the Model and attached Behaviors
* to be used as validators
*
* @return array List of callables to be used as validation methods
*/
public function getMethods() {
if (!empty($this->_methods)) {
return $this->_methods;
}
$methods = array();
foreach (get_class_methods($this->_model) as $method) {
$methods[strtolower($method)] = array($this->_model, $method);
}
foreach (array_keys($this->_model->Behaviors->methods()) as $method) {
$methods += array(strtolower($method) => array($this->_model, $method));
}
return $this->_methods = $methods;
}
/**
* Returns a CakeValidationSet object containing all validation rules for a field, if no
* params are passed then it returns an array with all CakeValidationSet objects for each field
*
* @param string $name [optional] The fieldname to fetch. Defaults to null.
* @return CakeValidationSet|array
*/
public function getField($name = null) {
$this->_parseRules();
if ($name !== null && !empty($this->_fields[$name])) {
return $this->_fields[$name];
} elseif ($name !== null) {
return null;
}
return $this->_fields;
}
/**
* Sets the CakeValidationSet objects from the `Model::$validate` property
* If `Model::$validate` is not set or empty, this method returns false. True otherwise.
*
* @return boolean true if `Model::$validate` was processed, false otherwise
*/
protected function _parseRules() {
if ($this->_validate === $this->_model->validate) {
return true;
}
if (empty($this->_model->validate)) {
$this->_validate = array();
$this->_fields = array();
return false;
}
$this->_validate = $this->_model->validate;
$this->_fields = array();
$methods = $this->getMethods();
foreach ($this->_validate as $fieldName => $ruleSet) {
$this->_fields[$fieldName] = new CakeValidationSet($fieldName, $ruleSet);
$this->_fields[$fieldName]->setMethods($methods);
}
return true;
}
/**
* Sets the I18n domain for validation messages. This method is chainable.
*
* @param string $validationDomain [optional] The validation domain to be used.
* @return ModelValidator
*/
public function setValidationDomain($validationDomain = null) {
if (empty($validationDomain)) {
$validationDomain = 'default';
}
$this->getModel()->validationDomain = $validationDomain;
return $this;
}
/**
* Gets the model related to this validator
*
* @return Model
*/
public function getModel() {
return $this->_model;
}
/**
* Processes the Model's whitelist or passed fieldList and returns the list of fields
* to be validated
*
* @param array $fieldList list of fields to be used for validation
* @return array List of validation rules to be applied
*/
protected function _validationList($fieldList = array()) {
$model = $this->getModel();
$whitelist = $model->whitelist;
if (!empty($fieldList)) {
if (!empty($fieldList[$model->alias]) && is_array($fieldList[$model->alias])) {
$whitelist = $fieldList[$model->alias];
} else {
$whitelist = $fieldList;
}
}
unset($fieldList);
$validateList = array();
if (!empty($whitelist)) {
$this->validationErrors = array();
foreach ((array)$whitelist as $f) {
if (!empty($this->_fields[$f])) {
$validateList[$f] = $this->_fields[$f];
}
}
} else {
return $this->_fields;
}
return $validateList;
}
/**
* Runs validation for hasAndBelongsToMany associations that have 'with' keys
* set and data in the data set.
*
* @param array $options Array of options to use on Validation of with models
* @return boolean Failure of validation on with models.
* @see Model::validates()
*/
protected function _validateWithModels($options) {
$valid = true;
$model = $this->getModel();
foreach ($model->hasAndBelongsToMany as $assoc => $association) {
if (empty($association['with']) || !isset($model->data[$assoc])) {
continue;
}
list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
$data = $model->data[$assoc];
$newData = array();
foreach ((array)$data as $row) {
if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row;
} elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row[$join];
}
}
if (empty($newData)) {
continue;
}
foreach ($newData as $data) {
$data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
$model->{$join}->create($data);
$valid = ($valid && $model->{$join}->validator()->validates($options));
}
}
return $valid;
}
/**
* Propagates beforeValidate event
*
* @param array $options
* @return boolean
*/
protected function _triggerBeforeValidate($options = array()) {
$model = $this->getModel();
$event = new CakeEvent('Model.beforeValidate', $model, array($options));
list($event->break, $event->breakOn) = array(true, false);
$model->getEventManager()->dispatch($event);
if ($event->isStopped()) {
return false;
}
return true;
}
/**
* Returns wheter a rule set is defined for a field or not
*
* @param string $field name of the field to check
* @return boolean
**/
public function offsetExists($field) {
$this->_parseRules();
return isset($this->_fields[$field]);
}
/**
* Returns the rule set for a field
*
* @param string $field name of the field to check
* @return CakeValidationSet
**/
public function offsetGet($field) {
$this->_parseRules();
return $this->_fields[$field];
}
/**
* Sets the rule set for a field
*
* @param string $field name of the field to set
* @param array|CakeValidationSet $rules set of rules to apply to field
* @return void
**/
public function offsetSet($field, $rules) {
$this->_parseRules();
if (!$rules instanceof CakeValidationSet) {
$rules = new CakeValidationSet($field, $rules);
$methods = $this->getMethods();
$rules->setMethods($methods);
}
$this->_fields[$field] = $rules;
}
/**
* Unsets the rulset for a field
*
* @param string $field name of the field to unset
* @return void
**/
public function offsetUnset($field) {
$this->_parseRules();
unset($this->_fields[$field]);
}
/**
* Returns an iterator for each of the fields to be validated
*
* @return ArrayIterator
**/
public function getIterator() {
$this->_parseRules();
return new ArrayIterator($this->_fields);
}
/**
* Returns the number of fields having validation rules
*
* @return int
**/
public function count() {
$this->_parseRules();
return count($this->_fields);
}
/**
* Adds a new rule to a field's rule set. If second argumet is an array or instance of
* CakeValidationSet then rules list for the field will be replaced with second argument and
* third argument will be ignored.
*
* ## Example:
*
* {{{
* $validator
* ->add('title', 'required', array('rule' => 'notEmpty', 'required' => true))
* ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
*
* $validator->add('password', array(
* 'size' => array('rule' => array('between', 8, 20)),
* 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
* ));
* }}}
*
* @param string $field The name of the field from wich the rule will be removed
* @param string|array|CakeValidationSet $name name of the rule to be added or list of rules for the field
* @param array|CakeValidationRule $rule or list of rules to be added to the field's rule set
* @return ModelValidator this instance
**/
public function add($field, $name, $rule = null) {
$this->_parseRules();
if ($name instanceof CakeValidationSet) {
$this->_fields[$field] = $name;
return $this;
}
if (!isset($this->_fields[$field])) {
$rule = (is_string($name)) ? array($name => $rule) : $name;
$this->_fields[$field] = new CakeValidationSet($field, $rule);
} else {
if (is_string($name)) {
$this->_fields[$field]->setRule($name, $rule);
} else {
$this->_fields[$field]->setRules($name);
}
}
$methods = $this->getMethods();
$this->_fields[$field]->setMethods($methods);
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 wich the rule will be removed
* @param string $rule the name of the rule to be removed
* @return ModelValidator this instance
**/
public function remove($field, $rule = null) {
$this->_parseRules();
if ($rule === null) {
unset($this->_fields[$field]);
} else {
$this->_fields[$field]->removeRule($rule);
}
return $this;
}
}
|