я же говорю. класс должен работать с массивов данных формы.
Winston заразил меня CI
$data = array(
array(
'field'=> 'login',
'label'=> 'Логин',
'value'=> 'p222222',
'rule' => 'lenght',
'pattern' => '3,5'
),
array(
'field'=> 'phone',
'label'=> 'Телефон',
'value'=> '2651200',
'rule' => 'regexp',
'pattern' => '\([0-9]{3,4}\)[0-9]{3}\-[0-9]{2}\-[0-9]{2}'
),
array(
'field'=> 'years',
'label'=> 'Полных лет',
'value'=> 23,
'rule' => 'int',
),
array(
'field'=> 'price',
'label'=> 'Цена',
'value'=> 23.01,
'rule' => 'float',
),
array(
'field'=> 'email',
'label'=> 'Мыло',
'value'=> 'support@guugle.ru',
'rule' => 'email',
),
);
В итоге - действительно - использование мелких приватных методов (которые можно было вынести и в интерфейсы наверно, но цель - в одном классе) - позволили сделать - удобный, легкрасширяемый инструмет для работы с формами.
Вроде заключительная, но не полнофункциональная версия класса
class Validate{
public $mysqli;
public $result;
private $messages;
private $lenght;
public function __construct($data, $mysqli, $result = array(), $messages = array(), $lenght = array()){
$this->data = $data;
$this->messages = $messages;
$this->lenght = $lenght;
$this->result = $result;
$this->mysqli = $mysqli;
}
private function message($label=null, $rule=null){
$this->lenght = (isset($this->lenght[0]) || isset($this->lenght[1])) ? $this->lenght : $this->lenght = array('','');
$this->messages = array(
'error' => 'Не правильный формат данных',
'int' => 'Поле "'.$label.'" должно содержать только цифры',
'float'=> 'Поле "'.$label.'" должно содержать десятичную дробь',
'regexp'=>'Поле "'.$label.'" заполнено не верно',
'lenght-min'=> 'Поле "'.$label.'" должно содержать минимум '.$this->lenght[0].' символа(ов)',
'lenght-max'=> 'Поле "'.$label.'" должно содержать максимум '.$this->lenght[1].' символа(ов)',
'email' => 'Не правильный формат email',
);
return $this->messages[$rule];
}
private function v_int($value){
return (!is_int($value)) ? false : true;
}
private function v_float($value){
$v['value'] = strtr($value, array(','=>'.'));
return (!is_float($value)) ? false : true;
}
private function v_regexp($pattern, $value){
return (!preg_match('#'.$pattern.'#iusU', $value)) ? false : true;
}
private function v_lenght_min($pattern, $value){
$this->lenght = explode(',',$pattern);
return (mb_strlen($value, 'utf-8') < $this->lenght[0]) ? false : true;
}
private function v_lenght_max($pattern, $value){
$this->lenght = explode(',',$pattern);
return (mb_strlen($value, 'utf-8') > $this->lenght[1]) ? false : true;
}
private function v_email($value){
return (!filter_var($value, FILTER_VALIDATE_EMAIL)) ? false : true;
}
public function combine(){
if(!is_array($this->data) && !isset($data[0])){
$this->result['error']['data'] = $this->message(null, 'error');
return $this->result;
}
else{
foreach($this->data as $k=>$v){
switch($v['rule']){
case 'int':
$temp = (!$this->v_int($v['value'])) ? false : true;
break;
case 'float':
$temp = (!$this->v_float($v['value'])) ? false : true;
break;
case 'regexp':
$temp = (!$this->v_regexp($v['pattern'], $v['value'])) ? false : true;
break;
case 'lenght':
if(!$this->v_lenght_min($v['pattern'], $v['value'])){
$temp = (!$this->v_lenght_min($v['pattern'], $v['value'])) ? false : true;
$v['rule'] = 'lenght-min';
}
elseif(!$this->v_lenght_max($v['pattern'], $v['value'])){
$temp = (!$this->v_lenght_max($v['pattern'], $v['value'])) ? false : true;
$v['rule'] = 'lenght-max';
}
else{
$temp = true;
}
break;
case 'email':
$temp = (!$this->v_email($v['value'])) ? false : true;
break;
}
if($temp === true){
$this->result['success'][$v['field']]= array(
'value' => is_string($v['value']) ? $this->mysqli->escape_string($v['value']) : $v['value'],
'lenght' => mb_strlen($v['value'], 'utf-8')
);
}
else{
if(!$this->v_int($v['value'])){
$this->result['errors'][$v['field']] = array(
'value' => htmlspecialchars($v['value']),
'message'=>$this->message($v['label'], $v['rule'])
);
}
}
}
}
return $this->result;
}
}
Работает с выше обозначенным массивом данных
$validate = new Validate($data, $mysqli);
$result = $validate->combine();
echo '<pre>' . print_r($result, 1) . '</pre>';
Array
(
[errors] => Array
(
[login] => Array
(
[value] => p222222
[message] => Поле "Логин" должно содержать максимум 5 символа(ов)
)
[phone] => Array
(
[value] => 2651200
[message] => Поле "Телефон" заполнено не верно
)
)
[success] => Array
(
[years] => Array
(
[value] => 23
[lenght] => 2
)
[price] => Array
(
[value] => 23.01
[lenght] => 5
)
[email] => Array
(
[value] => support@guugle.ru
[lenght] => 17
)
)
)
Проверяем empty$result['errors'] - и если пуст - работаем.
:P
_____________
HTML, CSS (Bootstrap), JS(JQuery, ExtJS), PHP, MySQL, MSSql, Posgres, (TSql, BI OLAP, MDX), Mongo, Git, SVN, CodeIgnater, Symfony, Yii 2, JiRA, Redmine, Bitbucket, Composer, Rabbit MQ, Amazon (SQS, S3, Transcribe), Docker