Skip to content

Instantly share code, notes, and snippets.

@ashour
Last active February 13, 2020 10:54
Show Gist options
  • Save ashour/854dc08e776c2f72bd6884d4925d5d31 to your computer and use it in GitHub Desktop.
Save ashour/854dc08e776c2f72bd6884d4925d5d31 to your computer and use it in GitHub Desktop.
<?php
require_once dirname(__FILE__) . '/../i18n/I18n.php';
class Validator
{
// ...
public function isAllValid()
{
$this->errors = [];
// We spin on each field's defined rules, calling each one reflectively.
// We stop at the first rule for a field that _doesn't_ pass, if one
// exists. And, if we have a failing rule for a field, we add it to our
// errors array.
foreach ($this->rules as $field => $fieldRules) {
$value = $this->fields[$field] ?? null;
foreach ($fieldRules as $rule) {
// Some rules, like min(imum) length, have arguments. So
// we parse each rule (min|6) to separate the name (min)
// from the argument (6).
[$ruleName, $ruleArg] = $this->parseRule($rule);
$validateMethod = "validate_{$ruleName}";
if (!$this->$validateMethod($value, $ruleArg)) {
$this->errors[$field] =
$this->getErrorText($field, $ruleName, $ruleArg);
break;
}
}
}
return count($this->errors) == 0;
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment