Skip to content

Instantly share code, notes, and snippets.

@jyokyoku
Created October 9, 2011 10:53
Show Gist options
  • Save jyokyoku/1273549 to your computer and use it in GitHub Desktop.
Save jyokyoku/1273549 to your computer and use it in GitHub Desktop.
CakePHP AssocFieldValidationBehavior
<?php
class AssocFieldValidationBehavior extends ModelBehavior
{
public function checkAssocField($Model, $check, $assocField, $assocValueList = null, $delegateRule = null)
{
$key = 0;
if (is_array($check)) {
list($key, $check) = each($check);
}
if (strpos($assocField, '.') !== false) {
list($model, $assocField) = $assocField;
} else {
$model = $Model->alias;
}
$assocValue = Set::extract($Model->data, "{$model}.{$assocField}");
if ($this->_isValidator($assocValueList) || !$assocValueList) {
$assocValueList = null;
}
if (empty($assocValue) || ($assocValueList && !in_array($assocValue, (array)$assocValueList))) {
return true;
}
if ($this->_isValidator($delegateRule) || !$delegateRule) {
$delegateRule = 'notEmpty';
}
if (is_array($delegateRule)) {
$rule = array_shift($delegateRule);
$ruleParams = array_merge(array($check), $delegateRule);
} else {
$rule = $delegateRule;
$ruleParams = array($check);
}
$Validation = Validation::getInstance();
$methods = array_map('strtolower', get_class_methods($Model));
$behaviorMethods = array_diff(array_keys($Model->Behaviors->methods()), array(__FUNCTION__));
if (in_array(strtolower($rule), $methods)) {
$ruleParams[0] = array($key => $check);
$valid = $Model->dispatchMethod($rule, $ruleParams);
} else if (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
$ruleParams[0] = array($key => $check);
$valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
} else if (method_exists($Validation, $rule)) {
$valid = $Validation->dispatchMethod($rule, $ruleParams);
} else if (!is_array($delegateRule)) {
$valid = preg_match($rule, $check);
} else {
$valid = false;
}
return $valid;
}
protected function _isValidator($array)
{
return (is_array($array) && isset($array['allowEmpty'], $array['required']));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment