Custom Validators
Validators must implement Centum\Interfaces\Validator\ValidatorInterface
.
Validators only require the following public methods:
validate(mixed $value): list<non-empty-string>
The validate()
method returns an array of violations as strings. An empty array has no violations meaning that the value is valid.
As an example, a Validator can be made to check the a value is not empty:
namespace App\Validators;
use Centum\Interfaces\Validator\ValidatorInterface;
class NotEmptyValidator implements ValidatorInterface
{
public function validate(mixed $value): array
{
if (empty($value)) {
return [
"Value is required and can't be empty.",
];
}
return [];
}
}
(see also Centum\Validator\NotEmpty
).
More complex Validators can be made by injecting other objects into the validator:
namespace App\Validators;
use Centum\Interfaces\Validator\ValidatorInterface;
use DatePeriod;
use DateTimeInterface;
class WithinDatePeriodValidator implements ValidatorInterface
{
public function __construct(
protected readonly DatePeriod $datePeriod
) {
}
public function validate(mixed $value): array
{
if (!($value instanceof DateTimeInterface)) {
return [
"Value is not a DateTimeInterface",
];
}
foreach ($this->datePeriod as $dateTime) {
if ($dateTime->format("U") === $value->format("U")) {
return [];
}
}
return [
"Value is not in date period.",
];
}
}