Skip to content

Custom rules ​

There are three ways, from the simplest.

A callback ​

For a one-off check, use callback with the expectation that completes "… must …":

php
Assert::callback(Assert::ref('n'), static fn (mixed $n): bool => is_int($n) && $n % 2 === 0, 'be even');
// n must be even

The callback gets the value, and not() works on it like on any rule: n must not be even.

A predicate ​

Rules\Predicate is what every built-in leaf rule is. It takes named operands, a test, and an expectation in which {name} stands for the label of an operand. Wrap it in a function to reuse it:

php
use EugeneErg\Assert\Expressions\Operands;
use EugeneErg\Assert\Rules\Predicate;

function isbn(mixed $subject): Predicate
{
    return new Predicate(
        'isbn',                                            // the violation code
        ['value' => $subject],                             // operands: the first one is the subject
        static fn (Operands $operands): bool => is_string($operands->value('value'))
            && preg_match('/^\d{13}$/', $operands->value('value')) === 1,
        'be an ISBN-13',
    );
}

isbn(Assert::ref('isbn'))->violations(['isbn' => '123']);  // isbn must be an ISBN-13

Literal operands must be wrapped in Expressions\Literal; Assert::ref() and Assert::value() are already expressions.

Predicates also take guards: per-operand preconditions that report invalid and are never negated.

A Rule subclass ​

For full control, extend EugeneErg\Assert\Rule and implement check(). It gets the current node of the data and whether the rule is negated, and returns the violations:

php
use EugeneErg\Assert\Context;
use EugeneErg\Assert\Expressions\Ref;
use EugeneErg\Assert\Rule;
use EugeneErg\Assert\Violation;

final readonly class Even extends Rule
{
    public function __construct(private Ref $subject) {}

    public function check(Context $context, bool $negated = false): array
    {
        $node = $context->resolve($this->subject);

        if (!is_int($node->value)) {
            return [new Violation(Violation::INVALID, $node->path, $node->label() . ' must be of type int, ' . get_debug_type($node->value) . ' given')];
        }

        if (($node->value % 2 === 0) !== $negated) {
            return [];
        }

        return [new Violation('even', $node->path, $node->label() . ' must ' . ($negated ? 'not ' : '') . 'be even', ['value' => $node->value], $negated)];
    }
}

The contract: return an empty list when the rule holds, which means "is even" normally and "is not even" when $negated is true. Report what cannot be checked at all as invalid whatever $negated is.