Not saying this is exactly how I'd do it, but trying to keep your general idea and just breaking things up into more atomic pieces, maybe:
<?php
class FormValidation {
protected $errors = [];
public function validateFields(Array $fields, Array $rules) {
$this->errors = [];
foreach($fields as $field => $value) {
if(isset($rules[$field])) {
foreach($rules[$field] as $rule => $param) {
$this->validate($field, $value, $rule, $param);
}
}
}
return empty($this->errors);
}
public function errors() {
return $this->errors;
}
protected function validate($name, $input, $validationType, $validationValue=null) {
if(!$this->$validationType($input, $validationValue)) {
$this->errors[$name][$validationType] = $validationValue;
}
}
protected function required($input, $value=null) {
return !empty(trim($input));
}
protected function minLength($input, $length) {
return $this->length($input) >= $length;
}
protected function maxLength($input, $length) {
return $this->length($input) <= $length;
}
protected function length($input) {
return strlen(trim($input));
}
}
// TEST
$validationRules = [
'first_name' => [
'required' => true,
'minLength' => 2,
'maxLength' => 40
],
'last_name' => [
'required' => true,
'minLength' => 2,
'maxLength' => 40
],
'middle_name' => [
'required' => false,
'maxLength' => 40
]
];
$validator = new FormValidation();
$testData = [
'first_name' => 'Nog',
'last_name' => 'Dog',
'middle_name' => 'X',
];
echo "Should pass:\n";
$test = $validator->validateFields($testData, $validationRules);
var_dump($test);
var_export($validator->errors());
$testData = [
'first_name' => ' ',
'last_name' => 'Dog',
'middle_name' => 'Xdkdkdkdkdkdkdkdkdkdkdkdddddddasdfasdfasdfasdfasdfasdfasdfadfsasdfasdfasdf',
];
echo "Should fail:\n";
$test = $validator->validateFields($testData, $validationRules);
var_dump($test);
var_export($validator->errors());
Output:
$ php validator.php
Should pass:
bool(true)
array (
)
Should fail:
bool(false)
array (
'first_name' =>
array (
'required' => true,
'minLength' => 2,
),
'middle_name' =>
array (
'maxLength' => 40,
),
)