<?php
require "errorHandler.php";
require "Validator.php";
$errorHandler = new ErrorHandler;
if(!empty($_POST))
{
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'username' =>[
'required'=> true,
'maxlength' => 20,
'minlength' => 3
]
]);
if($validation->fails())
{
echo '<pre>' . print_r($validation->errors()->all()) . '</pre>';
}
}
?>
<?php
class ErrorHandler
{
protected $errors = [];
public function addError($error, $key = null)
{
if($key)
{
$this->errors[$key][] = $error;
}
else
{
$this->errors[] = $error;
}
}
public function all($key = null)
{
return isset($this->errors[$key]) ? $this->errors[$key] : $this->errors;
}
public function hasErrors()
{
return count($this->all()) ? true : false;
}
public function first($key)
{
return isset($this->all()[$key][0]) ? $this->all()[$key][0]: false;
}
}
<?php
class Validator
{
protected $errorHandler;
protected $rules = ['required', 'minlength', 'maxlength', 'email'];
public $messages = [
'required' => 'The :field field is required',
'minlength' => 'The :field field must be a min of :satisfier',
'maxlength' => 'The :field field must be a min of :satisfier',
'email' => 'nope'
];
public function __construct(ErrorHandler $errorHandler)
{
$this->errorHandler = $errorHandler;
}
public function check($items, $rules)
{
foreach($items as $item => $value)
{
foreach($items as $item => $value)
{
if(in_array($item, array_keys($rules)))
{
$this->validate([
'field' => $item,
'value' => $value,
'rules' => $rules[$item]
]);
}
}
}
return $this;
}
public function fails()
{
return $this->errorHandler->hasErrors();
}
protected function validate($item)
{
$field = $item['field'];
foreach($item['rules'] as $rule => $satisfier)
{
if(in_array($rule, $this->rules))
{
if(!call_user_func_array([$this, $rule], [$field, $item['value'], $satisfier]))
{
$this->errorHandler->addError(
str_replace([':field'], [':satisfier'], [$field, $satisfier], $this->messages[$rule]),
$field);
}
}
}
}
public function errors()
{
return $this->errorHandler;
}
protected function required($field, $value, $satisfier)
{
return !empty(trim($value));
}
protected function minlength($field, $value, $satisfier)
{
return mb_strlen($value) >= $satisfier;
}
protected function maxlength($field, $value, $satisfier)
{
return mb_strlen($value) <= $satisfier;
}
protected function email($field, $value, $satisfier)
{
return filter_var($value, FILTER_VALIDATE_EMAIL);
}
}
Seems so so