Skip to content

Validator interface

composer require quillstack/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-interface

Usage

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

InterfaceWhat it means
ValidatorInterfacevalidate(): bool — the thing validates something
ValidatorExceptionInterfacesomething went wrong in a validator
ValidationExceptionInterfacethe 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

There is nothing to run here: a package which only names things has no behaviour to test.

License

MIT. See LICENSE.

Released under the MIT License.