Files
project-manager/src/Support/Validator.php
T

142 lines
3.3 KiB
PHP
Raw Normal View History

2026-09-03 18:30:52 +01:00
<?php
declare(strict_types=1);
namespace App\Support;
use App\Exception\ValidationException;
/**
* Small helper for validating a decoded JSON request body. Accumulates
* field => messages and throws a ValidationException when asked.
*/
final class Validator
{
/** @var array<string, string[]> */
private array $errors = [];
/**
* @param array<string, mixed> $data
*/
public function __construct(private readonly array $data)
{
}
public function has(string $field): bool
{
return array_key_exists($field, $this->data);
}
/**
* A required, non-blank, length-bounded string.
*/
public function requiredString(string $field, int $max, int $min = 1): string
{
if (!$this->has($field) || $this->data[$field] === null) {
$this->errors[$field][] = ucfirst($field) . ' is required.';
return '';
}
return $this->stringValue($field, $max, $min) ?? '';
}
/**
* An optional string; returns null when the field is absent.
*/
public function optionalString(string $field, int $max, int $min = 0): ?string
{
if (!$this->has($field)) {
return null;
}
return $this->stringValue($field, $max, $min);
}
public function optionalBool(string $field): ?bool
{
if (!$this->has($field)) {
return null;
}
$value = $this->data[$field];
if (is_bool($value)) {
return $value;
}
if ($value === 0 || $value === 1) {
return $value === 1;
}
$this->errors[$field][] = ucfirst($field) . ' must be true or false.';
return null;
}
public function optionalInt(string $field, int $min): ?int
{
if (!$this->has($field)) {
return null;
}
$value = $this->data[$field];
if (!is_int($value) || $value < $min) {
$this->errors[$field][] = ucfirst($field) . " must be an integer of at least {$min}.";
return null;
}
return $value;
}
public function add(string $field, string $message): void
{
$this->errors[$field][] = $message;
}
public function failed(): bool
{
return $this->errors !== [];
}
/**
* @throws ValidationException when any errors were recorded.
*/
public function assert(): void
{
if ($this->errors !== []) {
throw new ValidationException($this->errors);
}
}
private function stringValue(string $field, int $max, int $min): ?string
{
$value = $this->data[$field];
if (!is_string($value)) {
$this->errors[$field][] = ucfirst($field) . ' must be a string.';
return null;
}
$value = trim($value);
$length = mb_strlen($value);
if ($length < $min) {
$this->errors[$field][] = $min === 1
? ucfirst($field) . ' cannot be empty.'
: ucfirst($field) . " must be at least {$min} characters.";
return null;
}
if ($length > $max) {
$this->errors[$field][] = ucfirst($field) . " must be at most {$max} characters.";
return null;
}
return $value;
}
}