settings[$model->name] = $params; } /* in case we need to restore the validation */ function afterSave(&$model) { if($this->savedValidation && is_array($this->savedValidation) && in_array($model->name, $this->savedValidation)) { $model->validate = $this->savedValidation[$model->name]; unset($this->savedValidation[$model->name]); } } // set the model $validate array function beforeValidate(&$model) { if(empty($this->settings[$model->name])) return; if(isset($this->settings[$model->name]['restore']) && $this->settings[$model->name]['restore']) $this->savedValidation[$model->name] = $model->validate; /* the data in condition must be coded as $data['Model']['field'] (do not use $this->data) */ foreach($this->settings[$model->name] as $condition) { /* avoid the "restore" parameter */ if(!is_array($condition)) continue; if(isset($condition['condition']) && !empty($condition['condition'])) { if(method_exists($model, $condition['condition'])) { $rc = $model->{$condition['condition']}(); } else { $f = create_function('&$data', $this->_formatCondition($condition['condition'])); $rc = $f($model->data); } } else $rc = true; /* reference to this->data passed to the function to evaluate the condition, if 'condition' is not present, the condition will be assumed as true */ if($rc) { $option = array_merge(array('remove' => array(), 'validate' => array()), $condition); /* remove the fields in $validate */ if(!empty($option['remove'])) { foreach($option['remove'] as $rmfield) unset($model->validate[$rmfield]); } /* add some fields to validate */ if(!empty($option['validate'])) { foreach($option['validate'] as $key => $addfield) $model->validate[$key] = $addfield; } } } return; } // check the fields in conditions "Model.field" will be replace by $data['Model']['field'], sane with 'model.field' // They might be a better way (for more level), but I am not so confortable with regexp... // comments and suggestions are welcome function _formatCondition($condition) { $nb = preg_match_all('/(\'|"|\b)+\w+\.+\w+\1/', $condition, $match, PREG_OFFSET_CAPTURE); if($nb) { $search = array('\'', '"', '.'); $rep = array('', '', '\'][\''); foreach($match[0] as $repfield) { $condition = str_replace($repfield[0], '$data[\''.str_replace($search, $rep, $repfield[0]).'\']', $condition); } } return 'return '.$condition.' ? true : false;'; } } ?>