我需要帮助重构一个函数(函数很长,以后可以分开)。
我有一个fields对象,它包含数据库表中的每一列,并且有一些关于列的附加信息,例如max_length
以及它是否可以为null。这些参数构成了我对该字段的验证规则的基础,但是由一些设置验证规则(尝试制作我自己的Grocery CRUD)补充。以下功能是组合由列信息确定的参数和用户信息的逻辑。大foreach的工作是删除系统已经设置的任何用户验证规则(Codeigniter不能有重复的规则)以及函数注释中的其他一些内容。
我使用的validation library是Codeigniter,函数所属的类存在于Codeigniter生态系统中。该函数接收字段的字段作为对象,并开始尝试生成类似于rule1|rule2|rule3[50]
的内容
这个功能起作用,在我看来很丑陋,而且我认为可能有更好的方法来实现我想要实现的目标。
$this->validation_rules[$field->name]
:array('content_short' => 'strip_tags|trim|required|max_length[400]')
/**
* Gets validation rules for a field
*
* Combines system rules and user rules
* Required enforced if column cannot be null
* Max length enforced for columns with max length attributes, overridden
* by user max length of a smaller value than that which the db specifies
* In list enforced for columns with type enum (if the field has user specified
* in_list it will be removed as db one takes precedence)
*
* Function is ugly as hell...
*
* @param obj $field
* @return boolean|string
*/
protected function field_validation_rules($field) {
$sys_rules = array();
if (!$field->null) {
//$sys_rules['trim'] = 'trim';
$sys_rules['required'] = 'required';
}
if (!is_null($field->max_length)) {
if ($field->db_type == 'enum') {
$opts = $this->parse_comma_separated($field->max_length);
foreach ($opts as $k => $v) {
$opts[$k] = trim(trim($v, '\''));
}
$values = implode(',', $opts);
$sys_rules['in_list'] = $values;
} else {
$sys_rules['max_length'] = $field->max_length;
}
}
$user_rules = array();
if (isset($this->validation_rules[$field->name])) {
if (count($sys_rules) == 0) {
return $this->validation_rules[$field->name];
} else {
$user_rules = explode('|', $this->validation_rules[$field->name]);
foreach ($user_rules as $index => $rule) {
$f_rule = preg_filter('/\[(.*?)\]/', '', $rule);
if (empty($f_rule)) {
$f_rule = $rule;
}
if (in_array($f_rule, array_keys($sys_rules))) {
if ($f_rule == 'max_length') {
$match = preg_match('/\[(.*?)\]/', $rule, $matches);
if (intval($matches[1]) > $field->max_length) {
unset($user_rules[$index]);
} else {
unset($sys_rules['max_length']);
}
} else {
unset($user_rules[$index]);
}
}
}
}
}
$sdata = array();
foreach ($sys_rules as $key => $val) {
if ($key == $val) {
$sdata[] = $key;
} else {
$sdata[] = $key . "[$val]";
}
}
$all_rules = array_merge($sdata, $user_rules);
if (count($all_rules) !== 0) {
return implode('|', $all_rules);
} else {
return false;
}
}
作为参考,该功能用作:
if (($rules = $this->field_validation_rules($fields_obj)) !== false) {
$this->CI->form_validation->set_rules($field_name, $fields_obj->human_name, $rules);
$i++;
}