From 2bb257006e8f2dd792c46c868b3bf80c5a25a64b Mon Sep 17 00:00:00 2001 From: Asko Nomm Date: Tue, 22 Feb 2022 17:54:18 +0100 Subject: Initial commit --- src/Validator.php | 111 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/Validator.php (limited to 'src/Validator.php') diff --git a/src/Validator.php b/src/Validator.php new file mode 100644 index 0000000..8d91bb9 --- /dev/null +++ b/src/Validator.php @@ -0,0 +1,111 @@ + 'test@example.com']; + * $validators = ['email' => 'required|email']; + * $validator = new Validator($fields, $validators); + * + * if ($validator->fails()) { + * return $validator->errors(); + * } + * ``` + * + * @author Asko Nomm + */ +class Validator +{ + private array $errors = []; + + public function __construct( + private array $fields, + private array $validators, + array $rules = [], + ) { + if (empty($rules)) { + $this->rules = $this->defaultRules(); + } + + $this->validate(); + } + + public function defaultRules(): array + { + return [ + 'len' => ValidatorRules::len(), + 'email' => ValidatorRules::email(), + 'required' => ValidatorRules::required(), + ]; + } + + /** + * Runs `$this->validators` over `$this->fields` to construct + * potential errors that will be stored as an array of strings + * in `$this->errors`. + * + * @return void + */ + private function validate(): void + { + foreach ($this->validators as $field => $validator) { + $value = $this->fields[$field]; + + foreach (explode('|', $validator) as $item) { + if (str_contains($item, ':')) { + [$name, $modifier] = explode(':', $item); + + if (!$this->rules[$name]['validates']($value, $modifier)) { + $this->errors[] = $this->rules[$name]['error']($field, $modifier); + } + } else { + + if (!$this->rules[$item]['validates']($value)) { + $this->errors[] = $this->rules[$item]['error']($field); + } + } + } + } + } + + /** + * Returns a boolean `true` if there have been any errors. + * Returns `false` otherwise. + * + * @return boolean + */ + public function fails(): bool + { + return count($this->errors) !== 0; + } + + /** + * Returns an array of strings where each string + * is a single error that happened during validation. + */ + public function errors(): array + { + return $this->errors; + } + + public function firstError(): string + { + if (count($this->errors) > 0) { + return $this->errors[0]; + } + + return ''; + } +} -- cgit v1.2.3