Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 1
<?php
2
/**
3
 * ModelValidator.
4
 *
5
 * Provides the Model validation logic.
6
 *
7
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
9
 *
10
 * Licensed under The MIT License
11
 * For full copyright and license information, please see the LICENSE.txt
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
15
 * @link          http://cakephp.org CakePHP(tm) Project
16
 * @package       Cake.Model
17
 * @since         CakePHP(tm) v 2.2.0
18
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
19
 */
20
 
21
App::uses('CakeValidationSet', 'Model/Validator');
22
App::uses('Hash', 'Utility');
23
 
24
/**
25
 * ModelValidator object encapsulates all methods related to data validations for a model
26
 * It also provides an API to dynamically change validation rules for each model field.
27
 *
28
 * Implements ArrayAccess to easily modify rules as usually done with `Model::$validate`
29
 * definition array
30
 *
31
 * @package       Cake.Model
32
 * @link          http://book.cakephp.org/2.0/en/data-validation.html
33
 */
34
class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
35
 
36
/**
37
 * Holds the CakeValidationSet objects array
38
 *
39
 * @var array
40
 */
41
	protected $_fields = array();
42
 
43
/**
44
 * Holds the reference to the model this Validator is attached to
45
 *
46
 * @var Model
47
 */
48
	protected $_model = array();
49
 
50
/**
51
 * The validators $validate property, used for checking whether validation
52
 * rules definition changed in the model and should be refreshed in this class
53
 *
54
 * @var array
55
 */
56
	protected $_validate = array();
57
 
58
/**
59
 * Holds the available custom callback methods, usually taken from model methods
60
 * and behavior methods
61
 *
62
 * @var array
63
 */
64
	protected $_methods = array();
65
 
66
/**
67
 * Holds the available custom callback methods from the model
68
 *
69
 * @var array
70
 */
71
	protected $_modelMethods = array();
72
 
73
/**
74
 * Holds the list of behavior names that were attached when this object was created
75
 *
76
 * @var array
77
 */
78
	protected $_behaviors = array();
79
 
80
/**
81
 * Constructor
82
 *
83
 * @param Model $Model A reference to the Model the Validator is attached to
84
 */
85
	public function __construct(Model $Model) {
86
		$this->_model = $Model;
87
	}
88
 
89
/**
90
 * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
91
 * that use the 'with' key as well. Since `Model::_saveMulti` is incapable of exiting a save operation.
92
 *
93
 * Will validate the currently set data. Use `Model::set()` or `Model::create()` to set the active data.
94
 *
95
 * @param array $options An optional array of custom options to be made available in the beforeValidate callback
96
 * @return bool True if there are no errors
97
 */
98
	public function validates($options = array()) {
99
		$errors = $this->errors($options);
100
		if (empty($errors) && $errors !== false) {
101
			$errors = $this->_validateWithModels($options);
102
		}
103
		if (is_array($errors)) {
104
			return count($errors) === 0;
105
		}
106
		return $errors;
107
	}
108
 
109
/**
110
 * Validates a single record, as well as all its directly associated records.
111
 *
112
 * #### Options
113
 *
114
 * - atomic: If true (default), returns boolean. If false returns array.
115
 * - fieldList: Equivalent to the $fieldList parameter in Model::save()
116
 * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
117
 *
118
 * Warning: This method could potentially change the passed argument `$data`,
119
 * If you do not want this to happen, make a copy of `$data` before passing it
120
 * to this method
121
 *
122
 * @param array &$data Record data to validate. This should be an array indexed by association name.
123
 * @param array $options Options to use when validating record data (see above), See also $options of validates().
124
 * @return array|bool If atomic: True on success, or false on failure.
125
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
126
 *    depending on whether each record validated successfully.
127
 */
128
	public function validateAssociated(&$data, $options = array()) {
129
		$model = $this->getModel();
130
		$options += array('atomic' => true, 'deep' => false);
131
		$model->validationErrors = $validationErrors = $return = array();
132
		$model->create(null);
133
		$return[$model->alias] = true;
134
		if (!($model->set($data) && $model->validates($options))) {
135
			$validationErrors[$model->alias] = $model->validationErrors;
136
			$return[$model->alias] = false;
137
		}
138
		$data = $model->data;
139
		if (!empty($options['deep']) && isset($data[$model->alias])) {
140
			$recordData = $data[$model->alias];
141
			unset($data[$model->alias]);
142
			$data += $recordData;
143
		}
144
 
145
		$associations = $model->getAssociated();
146
		foreach ($data as $association => &$values) {
147
			$validates = true;
148
			if (isset($associations[$association])) {
149
				if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
150
					if ($options['deep']) {
151
						$validates = $model->{$association}->validateAssociated($values, $options);
152
					} else {
153
						$model->{$association}->create(null);
154
						$validates = $model->{$association}->set($values) && $model->{$association}->validates($options);
155
						$data[$association] = $model->{$association}->data[$model->{$association}->alias];
156
					}
157
					if (is_array($validates)) {
158
						$validates = !in_array(false, Hash::flatten($validates), true);
159
					}
160
					$return[$association] = $validates;
161
				} elseif ($associations[$association] === 'hasMany') {
162
					$validates = $model->{$association}->validateMany($values, $options);
163
					$return[$association] = $validates;
164
				}
165
				if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
166
					$validationErrors[$association] = $model->{$association}->validationErrors;
167
				}
168
			}
169
		}
170
 
171
		$model->validationErrors = $validationErrors;
172
		if (isset($validationErrors[$model->alias])) {
173
			$model->validationErrors = $validationErrors[$model->alias];
174
			unset($validationErrors[$model->alias]);
175
			$model->validationErrors = array_merge($model->validationErrors, $validationErrors);
176
		}
177
		if (!$options['atomic']) {
178
			return $return;
179
		}
180
		if ($return[$model->alias] === false || !empty($model->validationErrors)) {
181
			return false;
182
		}
183
		return true;
184
	}
185
 
186
/**
187
 * Validates multiple individual records for a single model
188
 *
189
 * #### Options
190
 *
191
 * - atomic: If true (default), returns boolean. If false returns array.
192
 * - fieldList: Equivalent to the $fieldList parameter in Model::save()
193
 * - deep: If set to true, all associated data will be validated as well.
194
 *
195
 * Warning: This method could potentially change the passed argument `$data`,
196
 * If you do not want this to happen, make a copy of `$data` before passing it
197
 * to this method
198
 *
199
 * @param array &$data Record data to validate. This should be a numerically-indexed array
200
 * @param array $options Options to use when validating record data (see above), See also $options of validates().
201
 * @return mixed If atomic: True on success, or false on failure.
202
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
203
 *    depending on whether each record validated successfully.
204
 */
205
	public function validateMany(&$data, $options = array()) {
206
		$model = $this->getModel();
207
		$options += array('atomic' => true, 'deep' => false);
208
		$model->validationErrors = $validationErrors = $return = array();
209
		foreach ($data as $key => &$record) {
210
			if ($options['deep']) {
211
				$validates = $model->validateAssociated($record, $options);
212
			} else {
213
				$model->create(null);
214
				$validates = $model->set($record) && $model->validates($options);
215
				$data[$key] = $model->data;
216
			}
217
			if ($validates === false || (is_array($validates) && in_array(false, Hash::flatten($validates), true))) {
218
				$validationErrors[$key] = $model->validationErrors;
219
				$validates = false;
220
			} else {
221
				$validates = true;
222
			}
223
			$return[$key] = $validates;
224
		}
225
		$model->validationErrors = $validationErrors;
226
		if (!$options['atomic']) {
227
			return $return;
228
		}
229
		return empty($model->validationErrors);
230
	}
231
 
232
/**
233
 * Returns an array of fields that have failed validation. On the current model. This method will
234
 * actually run validation rules over data, not just return the messages.
235
 *
236
 * @param string $options An optional array of custom options to be made available in the beforeValidate callback
237
 * @return array Array of invalid fields
238
 * @see ModelValidator::validates()
239
 */
240
	public function errors($options = array()) {
241
		if (!$this->_triggerBeforeValidate($options)) {
242
			return false;
243
		}
244
		$model = $this->getModel();
245
 
246
		if (!$this->_parseRules()) {
247
			return $model->validationErrors;
248
		}
249
 
250
		$fieldList = $model->whitelist;
251
		if (empty($fieldList) && !empty($options['fieldList'])) {
252
			if (!empty($options['fieldList'][$model->alias]) && is_array($options['fieldList'][$model->alias])) {
253
				$fieldList = $options['fieldList'][$model->alias];
254
			} else {
255
				$fieldList = $options['fieldList'];
256
			}
257
		}
258
 
259
		$exists = $model->exists();
260
		$methods = $this->getMethods();
261
		$fields = $this->_validationList($fieldList);
262
 
263
		foreach ($fields as $field) {
264
			$field->setMethods($methods);
265
			$field->setValidationDomain($model->validationDomain);
266
			$data = isset($model->data[$model->alias]) ? $model->data[$model->alias] : array();
267
			$errors = $field->validate($data, $exists);
268
			foreach ($errors as $error) {
269
				$this->invalidate($field->field, $error);
270
			}
271
		}
272
 
273
		$model->getEventManager()->dispatch(new CakeEvent('Model.afterValidate', $model));
274
		return $model->validationErrors;
275
	}
276
 
277
/**
278
 * Marks a field as invalid, optionally setting a message explaining
279
 * why the rule failed
280
 *
281
 * @param string $field The name of the field to invalidate
282
 * @param string $message Validation message explaining why the rule failed, defaults to true.
283
 * @return void
284
 */
285
	public function invalidate($field, $message = true) {
286
		$this->getModel()->validationErrors[$field][] = $message;
287
	}
288
 
289
/**
290
 * Gets all possible custom methods from the Model and attached Behaviors
291
 * to be used as validators
292
 *
293
 * @return array List of callables to be used as validation methods
294
 */
295
	public function getMethods() {
296
		$behaviors = $this->_model->Behaviors->enabled();
297
		if (!empty($this->_methods) && $behaviors === $this->_behaviors) {
298
			return $this->_methods;
299
		}
300
		$this->_behaviors = $behaviors;
301
 
302
		if (empty($this->_modelMethods)) {
303
			foreach (get_class_methods($this->_model) as $method) {
304
				$this->_modelMethods[strtolower($method)] = array($this->_model, $method);
305
			}
306
		}
307
 
308
		$methods = $this->_modelMethods;
309
		foreach (array_keys($this->_model->Behaviors->methods()) as $method) {
310
			$methods += array(strtolower($method) => array($this->_model, $method));
311
		}
312
 
313
		return $this->_methods = $methods;
314
	}
315
 
316
/**
317
 * Returns a CakeValidationSet object containing all validation rules for a field, if no
318
 * params are passed then it returns an array with all CakeValidationSet objects for each field
319
 *
320
 * @param string $name [optional] The fieldname to fetch. Defaults to null.
321
 * @return CakeValidationSet|array
322
 */
323
	public function getField($name = null) {
324
		$this->_parseRules();
325
		if ($name !== null) {
326
			if (!empty($this->_fields[$name])) {
327
				return $this->_fields[$name];
328
			}
329
			return null;
330
		}
331
		return $this->_fields;
332
	}
333
 
334
/**
335
 * Sets the CakeValidationSet objects from the `Model::$validate` property
336
 * If `Model::$validate` is not set or empty, this method returns false. True otherwise.
337
 *
338
 * @return bool true if `Model::$validate` was processed, false otherwise
339
 */
340
	protected function _parseRules() {
341
		if ($this->_validate === $this->_model->validate) {
342
			return true;
343
		}
344
 
345
		if (empty($this->_model->validate)) {
346
			$this->_validate = array();
347
			$this->_fields = array();
348
			return false;
349
		}
350
 
351
		$this->_validate = $this->_model->validate;
352
		$this->_fields = array();
353
		$methods = $this->getMethods();
354
		foreach ($this->_validate as $fieldName => $ruleSet) {
355
			$this->_fields[$fieldName] = new CakeValidationSet($fieldName, $ruleSet);
356
			$this->_fields[$fieldName]->setMethods($methods);
357
		}
358
		return true;
359
	}
360
 
361
/**
362
 * Sets the I18n domain for validation messages. This method is chainable.
363
 *
364
 * @param string $validationDomain [optional] The validation domain to be used.
365
 * @return $this
366
 */
367
	public function setValidationDomain($validationDomain = null) {
368
		if (empty($validationDomain)) {
369
			$validationDomain = 'default';
370
		}
371
		$this->getModel()->validationDomain = $validationDomain;
372
		return $this;
373
	}
374
 
375
/**
376
 * Gets the model related to this validator
377
 *
378
 * @return Model
379
 */
380
	public function getModel() {
381
		return $this->_model;
382
	}
383
 
384
/**
385
 * Processes the passed fieldList and returns the list of fields to be validated
386
 *
387
 * @param array $fieldList list of fields to be used for validation
388
 * @return array List of validation rules to be applied
389
 */
390
	protected function _validationList($fieldList = array()) {
391
		if (empty($fieldList) || Hash::dimensions($fieldList) > 1) {
392
			return $this->_fields;
393
		}
394
 
395
		$validateList = array();
396
		$this->validationErrors = array();
397
		foreach ((array)$fieldList as $f) {
398
			if (!empty($this->_fields[$f])) {
399
				$validateList[$f] = $this->_fields[$f];
400
			}
401
		}
402
 
403
		return $validateList;
404
	}
405
 
406
/**
407
 * Runs validation for hasAndBelongsToMany associations that have 'with' keys
408
 * set and data in the data set.
409
 *
410
 * @param array $options Array of options to use on Validation of with models
411
 * @return bool Failure of validation on with models.
412
 * @see Model::validates()
413
 */
414
	protected function _validateWithModels($options) {
415
		$valid = true;
416
		$model = $this->getModel();
417
 
418
		foreach ($model->hasAndBelongsToMany as $assoc => $association) {
419
			if (empty($association['with']) || !isset($model->data[$assoc])) {
420
				continue;
421
			}
422
			list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
423
			$data = $model->data[$assoc];
424
 
425
			$newData = array();
426
			foreach ((array)$data as $row) {
427
				if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
428
					$newData[] = $row;
429
				} elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
430
					$newData[] = $row[$join];
431
				}
432
			}
433
			foreach ($newData as $data) {
434
				$data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
435
				$model->{$join}->create($data);
436
				$valid = ($valid && $model->{$join}->validator()->validates($options));
437
			}
438
		}
439
		return $valid;
440
	}
441
 
442
/**
443
 * Propagates beforeValidate event
444
 *
445
 * @param array $options Options to pass to callback.
446
 * @return bool
447
 */
448
	protected function _triggerBeforeValidate($options = array()) {
449
		$model = $this->getModel();
450
		$event = new CakeEvent('Model.beforeValidate', $model, array($options));
451
		list($event->break, $event->breakOn) = array(true, false);
452
		$model->getEventManager()->dispatch($event);
453
		if ($event->isStopped()) {
454
			return false;
455
		}
456
		return true;
457
	}
458
 
459
/**
460
 * Returns whether a rule set is defined for a field or not
461
 *
462
 * @param string $field name of the field to check
463
 * @return bool
464
 */
465
	public function offsetExists($field) {
466
		$this->_parseRules();
467
		return isset($this->_fields[$field]);
468
	}
469
 
470
/**
471
 * Returns the rule set for a field
472
 *
473
 * @param string $field name of the field to check
474
 * @return CakeValidationSet
475
 */
476
	public function offsetGet($field) {
477
		$this->_parseRules();
478
		return $this->_fields[$field];
479
	}
480
 
481
/**
482
 * Sets the rule set for a field
483
 *
484
 * @param string $field name of the field to set
485
 * @param array|CakeValidationSet $rules set of rules to apply to field
486
 * @return void
487
 */
488
	public function offsetSet($field, $rules) {
489
		$this->_parseRules();
490
		if (!$rules instanceof CakeValidationSet) {
491
			$rules = new CakeValidationSet($field, $rules);
492
			$methods = $this->getMethods();
493
			$rules->setMethods($methods);
494
		}
495
		$this->_fields[$field] = $rules;
496
	}
497
 
498
/**
499
 * Unsets the rule set for a field
500
 *
501
 * @param string $field name of the field to unset
502
 * @return void
503
 */
504
	public function offsetUnset($field) {
505
		$this->_parseRules();
506
		unset($this->_fields[$field]);
507
	}
508
 
509
/**
510
 * Returns an iterator for each of the fields to be validated
511
 *
512
 * @return ArrayIterator
513
 */
514
	public function getIterator() {
515
		$this->_parseRules();
516
		return new ArrayIterator($this->_fields);
517
	}
518
 
519
/**
520
 * Returns the number of fields having validation rules
521
 *
522
 * @return int
523
 */
524
	public function count() {
525
		$this->_parseRules();
526
		return count($this->_fields);
527
	}
528
 
529
/**
530
 * Adds a new rule to a field's rule set. If second argument is an array or instance of
531
 * CakeValidationSet then rules list for the field will be replaced with second argument and
532
 * third argument will be ignored.
533
 *
534
 * ## Example:
535
 *
536
 * {{{
537
 *		$validator
538
 *			->add('title', 'required', array('rule' => 'notEmpty', 'required' => true))
539
 *			->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
540
 *
541
 *		$validator->add('password', array(
542
 *			'size' => array('rule' => array('between', 8, 20)),
543
 *			'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
544
 *		));
545
 * }}}
546
 *
547
 * @param string $field The name of the field where the rule is to be added
548
 * @param string|array|CakeValidationSet $name name of the rule to be added or list of rules for the field
549
 * @param array|CakeValidationRule $rule or list of rules to be added to the field's rule set
550
 * @return $this
551
 */
552
	public function add($field, $name, $rule = null) {
553
		$this->_parseRules();
554
		if ($name instanceof CakeValidationSet) {
555
			$this->_fields[$field] = $name;
556
			return $this;
557
		}
558
 
559
		if (!isset($this->_fields[$field])) {
560
			$rule = (is_string($name)) ? array($name => $rule) : $name;
561
			$this->_fields[$field] = new CakeValidationSet($field, $rule);
562
		} else {
563
			if (is_string($name)) {
564
				$this->_fields[$field]->setRule($name, $rule);
565
			} else {
566
				$this->_fields[$field]->setRules($name);
567
			}
568
		}
569
 
570
		$methods = $this->getMethods();
571
		$this->_fields[$field]->setMethods($methods);
572
 
573
		return $this;
574
	}
575
 
576
/**
577
 * Removes a rule from the set by its name
578
 *
579
 * ## Example:
580
 *
581
 * {{{
582
 *		$validator
583
 *			->remove('title', 'required')
584
 *			->remove('user_id')
585
 * }}}
586
 *
587
 * @param string $field The name of the field from which the rule will be removed
588
 * @param string $rule the name of the rule to be removed
589
 * @return $this
590
 */
591
	public function remove($field, $rule = null) {
592
		$this->_parseRules();
593
		if ($rule === null) {
594
			unset($this->_fields[$field]);
595
		} else {
596
			$this->_fields[$field]->removeRule($rule);
597
		}
598
		return $this;
599
	}
600
}