Validator interface
Common interface for Validator classes.
One method, and two exception interfaces. Something which validates says so by implementing this, and something which fails validation says so by implementing the other — so a caller can tell a value it does not like from a mistake in the code.
Requirements
- PHP 8.1 or newer
Installation
shell
composer require quillstack/validator-interfaceUsage
php
use Quillstack\ValidatorInterface\ValidatorInterface;
final class HostValidator implements ValidatorInterface
{
public function __construct(private readonly string $host)
{
}
public function validate(): bool
{
if (filter_var($this->host, FILTER_VALIDATE_DOMAIN) === false) {
throw new UnknownHostException("Not a host: {$this->host}");
}
return true;
}
}The exception says which kind of thing went wrong:
php
use Quillstack\ValidatorInterface\ValidationExceptionInterface;
final class UnknownHostException extends UriException implements ValidationExceptionInterface
{
}Catching it is then catching one thing:
php
try {
$validator->validate();
} catch (ValidationExceptionInterface $exception) {
// What was given is wrong — not the code that was given it.
}Technical documentation
| Interface | What it means |
|---|---|
ValidatorInterface | validate(): bool — the thing validates something |
ValidatorExceptionInterface | something went wrong in a validator |
ValidationExceptionInterface | the value was wrong, which is the usual case; extends the one above |
validate() answers true or throws. It does not answer false: a caller which ignores the answer would carry on with a value nobody accepted, and a thrown exception cannot be ignored by accident.
Who implements it
- quillstack/uri — the scheme and the host of a URI
- quillstack/server-request — what
$_SERVERmust hold - quillstack/response — that a status code is one that exists
There is nothing to run here: a package which only names things has no behaviour to test.
License
MIT. See LICENSE.