| 14098 |
anikendra |
1 |
<?php
|
|
|
2 |
/**
|
|
|
3 |
* SubCollectionValidatorBehavior.
|
|
|
4 |
*
|
|
|
5 |
* Enalbe validation of subsets, used in some NoSQL
|
|
|
6 |
* Databases like MongoDB.
|
|
|
7 |
*
|
|
|
8 |
* PHP versions 5
|
|
|
9 |
*
|
|
|
10 |
* Copyright 2012, Radig Soluções em TI (http://radig.com.br)
|
|
|
11 |
*
|
|
|
12 |
* Licensed under The MIT License
|
|
|
13 |
* Redistributions of files must retain the above copyright notice.
|
|
|
14 |
*
|
|
|
15 |
* @copyright Copyright 2012, Radig Soluções em TI. (http://radig.com.br)
|
|
|
16 |
* @link http://github.com/radig/
|
|
|
17 |
* @package Mongodb.Model.Behavior
|
|
|
18 |
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
|
|
|
19 |
*/
|
|
|
20 |
|
|
|
21 |
App::uses('CakeValidationSet', 'Model/Validator');
|
|
|
22 |
class SubCollectionValidatorBehavior extends ModelBehavior {
|
|
|
23 |
|
|
|
24 |
private $_methods = array();
|
|
|
25 |
|
|
|
26 |
private $_Model = null;
|
|
|
27 |
|
|
|
28 |
public function setup(Model $model, $config = array()) {
|
|
|
29 |
if(!isset($this->_methods[$model->name])) {
|
|
|
30 |
$this->_methods[$model->name] = $model->validator()->getMethods();
|
|
|
31 |
}
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
public function beforeValidate(Model $model, $config = array()) {
|
|
|
35 |
$this->_Model = $model;
|
|
|
36 |
|
|
|
37 |
if(is_a($model->getDataSource(), 'Mongodbsource') && isset($model->collectionValidate)) {
|
|
|
38 |
foreach($model->data[$model->alias] as $fieldName => $value) {
|
|
|
39 |
if(!isset($model->collectionValidate[$fieldName])) {
|
|
|
40 |
continue;
|
|
|
41 |
}
|
|
|
42 |
|
|
|
43 |
$this->_validateCollection($model->data[$model->alias][$fieldName], $model->collectionValidate[$fieldName]);
|
|
|
44 |
}
|
|
|
45 |
}
|
|
|
46 |
|
|
|
47 |
return true;
|
|
|
48 |
}
|
|
|
49 |
|
|
|
50 |
public function beforeSave(Model $model, $config = array()) {
|
|
|
51 |
return empty($model->validationErrors);
|
|
|
52 |
}
|
|
|
53 |
|
|
|
54 |
protected function _validateCollection($data, $ruleset) {
|
|
|
55 |
foreach($data as $field => $value) {
|
|
|
56 |
if(is_array($value) && isset($ruleset["_{$field}"])) {
|
|
|
57 |
$status &= $this->_validateCollection($data[$field], $ruleset["_{$field}"]);
|
|
|
58 |
continue;
|
|
|
59 |
}
|
|
|
60 |
|
|
|
61 |
if(!isset($ruleset[$field])) {
|
|
|
62 |
continue;
|
|
|
63 |
}
|
|
|
64 |
|
|
|
65 |
$obj = new CakeValidationSet($field, $ruleset[$field]);
|
|
|
66 |
$obj->setMethods($this->_methods[$this->_Model->name]);
|
|
|
67 |
$errors = $obj->validate($data);
|
|
|
68 |
|
|
|
69 |
foreach($errors as $error) {
|
|
|
70 |
$this->_Model->invalidate($field, $error);
|
|
|
71 |
}
|
|
|
72 |
}
|
|
|
73 |
}
|
|
|
74 |
}
|