I updated my class with more functionality, but I kind if feel like it's a mess or that it can at least be improved by a bit readability, efficiency and/or DRY wise.
Anybody who could see if that can be done?
Any other suggestions are also welcome.
class Validator
{
private $errors = [];
private $rules = [];
public function getErrors($rulename = null)
{
if ($rulename) {
return isset($this->errors[$rulename]) ? $this->errors[$rulename] : null;
}
return $this->errors;
}
# rules will be checked against in order as specified
public function setRule($name, Array $rules, $required = true)
{
if (!array_key_exists($name, $this->rules)) {
foreach ($rules as $rule) {
if (!$rule instanceof IRule) {
throw new Exception('Array must only contain instances of IRule.');
}
}
$this->rules[$name]['rules'] = $rules;
if ($required === true) {
$this->rules[$name]['required'] = 'Must not be null or empty.';
} elseif ($required === false) {
$this->rules[$name]['required'] = false;
} else {
$this->rules[$name]['required'] = (String) $required;
}
} else {
throw new Exception(sprintf('Rule %s already exists.', $name));
}
}
public function validate($rulename, $input)
{
if ($this->rules[$rulename]['required']) {
if (empty($input)) {
$this->errors[$rulename][] = $this->rules[$rulename]['required'];
}
foreach ($this->rules[$rulename]['rules'] as $rule) {
try {
$rule->check($input);
} catch (Exception $e) {
$this->errors[$rulename][] = $e->getMessage();
}
}
if (isset($this->errors[$rulename])) {
return false;
}
} elseif (!empty($input)) {
foreach ($this->rules[$rulename]['rules'] as $rule) {
try {
$rule->check($input);
} catch (Exception $e) {
$this->errors[$rulename][] = $e->getMessage();
}
}
if (isset($this->errors[$rulename])) {
return false;
}
}
return true;
}
public function dump()
{
print_r($this->rules);
}
}