|
- <?php
-
- declare(strict_types=1);
-
- namespace Core;
-
- class Validator
- {
- protected array $errors = [];
-
- public function required(string $field, mixed $value, string $message = ''): self
- {
- if ($value === null || trim((string) $value) === '') {
- $this->errors[$field][] = $message ?: "{$field} is required.";
- }
-
- return $this;
- }
-
- public function maxLength(string $field, mixed $value, int $max, string $message = ''): self
- {
- if (strlen((string) $value) > $max) {
- $this->errors[$field][] = $message ?: "{$field} must be {$max} characters or fewer.";
- }
-
- return $this;
- }
-
- public function numeric(string $field, mixed $value, string $message = ''): self
- {
- if (!is_numeric($value)) {
- $this->errors[$field][] = $message ?: "{$field} must be numeric.";
- }
-
- return $this;
- }
-
- public function passes(): bool
- {
- return empty($this->errors);
- }
-
- public function fails(): bool
- {
- return !$this->passes();
- }
-
- public function errors(): array
- {
- return $this->errors;
- }
- }
|