/**
* 统一API参数检验方法
*
* 调用示例 check_param(array('money' => array('required', 'integer', 'greater_than_equal_to[1]', 'less_than_equal_to[200]')));
*
* @access public
* @param array $arr
* @since 1.0
* @return boolean
*/
public function check_param($arr, $data = array(), $method = 'get')
{
/**
* 设置要验证的请求数据
*/
if (!empty($arr)) {
$key_arr = array();
$rule_arr = array();
foreach ($arr as $key => $value) {
$temp_arr = explode(",", $key);
if (!is_array($value)) {
$value = explode("|", $value);
}
$key_arr = array_merge($key_arr, $temp_arr);
if (!empty($temp_arr)) {
foreach ($temp_arr as $temp_value) {
if (!empty($rule_arr[$temp_value])) {
$rule_arr[$temp_value] = array_merge($rule_arr[$temp_value], $value);
} else {
$rule_arr[$temp_value] = $value;
}
}
}
}
$key_arr = array_unique($key_arr);
if (!empty($rule_arr)) {
foreach ($rule_arr as $rule_key => $rule_value) {
$rule_arr[$rule_key] = array_unique($rule_value);
}
}
}
if ($method === 'post' || $method === 'POST') {
$request_data = $this->input->post($key_arr, TRUE);
} else {
$request_data = $this->input->get($key_arr, TRUE);
}
if ('get_post' == $method) {
$request_data = [];
foreach ($key_arr as $one_key) {
$request_data[$one_key] = $this->input->get_post($one_key, TRUE);
}
}
$raw_input_stream = $this->input->raw_input_stream;
// $raw_input_stream = stripslashes($raw_input_stream);
$input_stream = json_decode($raw_input_stream, TRUE);
if (json_last_error() === JSON_ERROR_NONE) {
foreach ($key_arr as $one_key) {
if (NULL === $request_data[$one_key] and isset($input_stream[$one_key])) {
$request_data[$one_key] = $input_stream[$one_key];
}
}
}
$this->form_validation->set_data($request_data);
/**
* 设置验证规则
*/
if (!empty($rule_arr)) {
$lang = $this->lang->line('txt_base_validation');
foreach ($rule_arr as $rule_key => $rule_value) {
$ts = $this->form_validation->set_rules($rule_key, '', $rule_value, array('required' => $lang[0]
, 'integer' => $lang[1]
, 'regex_match' => $lang[2]
, 'greater_than' => $lang[3]
, 'max_length' => $lang[4]
, 'min_length' => $lang[5]
));
}
}
/**
* 开始验证
*/
if (!$this->form_validation->run()) {
//验证失败处理逻辑
$errmsg = validation_errors(' ', ' ');
if (!empty($arr) && !empty($data)) {
foreach ($arr as $arr_key => $arr_value) {
$errmsg = str_replace($arr_key, $data[$arr_key], $errmsg);
}
}
$this->returnError($errmsg . $this->lang->line('txt_base_error_msg'), '400');
return FALSE;
}
return $request_data;
}