Skip to content

eugene-erg/assert ​

Composable, reusable validation rules for PHP 8.3+.

Documentation: https://eugeneerg.github.io/assert-docs/: guides, every rule with its message, recipes.

  • Chains for the common case. Assert::key('email')->isString()->matchesRegularExpression('/@/'), with optional(), nullable(), length() and count().
  • One entry point for everything else. Assert::* builds every rule. The first argument is the subject, and any argument can be a literal or a reference into the data.
  • References between fields. Compare min with max, or an item with a limit two levels up.
  • Negation done once, correctly. not() flips any rule, including all, any, each and some (by De Morgan's laws). Type preconditions are never negated: not(lessThan(x, 5)) still rejects null.
  • Structured violations. Every failure carries code, path, message, parameters and negated, so you can localize it or return it from an API.
php
use EugeneErg\Assert\Assert;
use EugeneErg\Assert\ValidationException;

$order = Assert::all(
    Assert::key('id')->isString()->length()->between(1, 36),
    Assert::key('minQty')->lessThanOrEqual(Assert::ref('maxQty')),
    Assert::key('items')->isArray()->each(Assert::all(
        Assert::key('sku')->exists(),
        Assert::key('qty')->between(Assert::parent(2, 'minQty'), Assert::parent(2, 'maxQty')),
    )),
    Assert::key('note')->optional()->nullable()->isString(),
);

try {
    $order->assert($data);
} catch (ValidationException $e) {
    // length of id must be greater than or equal to 1 and less than or equal to 36
    // items[1].sku must exist
    // items[1].qty must be greater than or equal to minQty and less than or equal to maxQty
    echo $e->getMessage();

    foreach ($e->violations as $violation) {
        $violation->code;       // "between"
        $violation->path;       // ["items", 1, "qty"]
        $violation->parameters; // ["value" => 9, "from" => 1, "to" => 5, ...]
    }
}

Each rule is an immutable object. Build it once and apply it to any number of values:

php
$rule->assert($data);      // throws ValidationException
$rule->validate($data);    // bool
$rule->violations($data);  // list<Violation>

Chains ​

Assert::key(...$path) starts a chain of rules about one key; Assert::that($subject) starts one about anything else. Every rule of Assert has a chain method without the subject argument, plus notEmpty(), rule(Rule) for any other rule, and each(Rule) / some(Rule) for elements.

  • In order. The rules run in order, and the chain stops at the first that fails: a number is not also reported as "not matching the pattern".
  • optional(). A missing key passes the whole chain.
  • nullable(). A null value passes the whole chain.
  • length() / count(). The next rules check the length or count instead of the value: ->isString()->length()->between(1, 100).

A chain is a rule: put it in all(), each(), not() or anywhere else.

Operands ​

ExpressionMeans
5, 'abc', [1, 2] …a literal
Assert::value()the value being checked (inside each/some: the current element)
Assert::ref('a', 'b')$value['a']['b']; works with arrays, ArrayAccess and public properties
Assert::parent(2, 'max')two levels up, then ['max']
Assert::length($x)number of characters in a string
Assert::count($x)number of elements in an array or Countable

A missing key resolves to null. Use Assert::exists() to require that the key is present.

Literals work too, so you can check values you already have:

php
Assert::lessThan($from, $to)->assert();

Rules ​

GroupRules
Chainskey, that
Logicall, any, not, each, some, when, optional
Presenceexists
Typestype($x, 'int|string'), isString, isInteger, isFloat, isBool, isNull, isArray, isObject, isIterable, isCallable, isNumeric, instanceOf
ClassesisA, isSubclassOf (class names are accepted only with allowString: true)
Valuesequal (strict by default), in, empty, callback
ComparisonlessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual, between
StringsmatchesRegularExpression, isRegularExpression

Comparison is strict about kinds. Numbers compare with numbers, strings with strings, and dates with dates. "10" is never compared with 9 silently: you get a violation with code invalid instead.

Type names follow get_debug_type(): int, float, string, bool, array, null, object, iterable, callable, numeric, scalar, mixed, or any class, interface or enum.

Conditions ​

php
// A missing key passes; a present one (even null) must be an int.
Assert::optional(Assert::ref('age'), Assert::isInteger(Assert::ref('age')));

// Companies need a VAT number, everyone else must not have one.
Assert::when(
    Assert::equal(Assert::ref('type'), 'company'),
    Assert::isString(Assert::ref('vat')),
    Assert::isNull(Assert::ref('vat')),
);

The condition only chooses a branch: its own failures are not reported. Under not(), the chosen branch is negated. Without an else branch, a failed condition is reported instead, so not(optional(...)) on a missing key gives "age must exist".

Violation codes ​

  • Rule name (lessThan, between, exists, type, …): the rule did not hold. negated is true when it was checked through not().
  • invalid: an operand cannot be checked by the rule at all (wrong type, unknown class, broken pattern). Negation does not apply here.
  • any: none of the alternatives held. The failed alternatives are listed in alternatives.
  • some: an iterable had no elements to satisfy some (or not(each)).

Custom rules ​

Extend EugeneErg\Assert\Rule and implement check(Context $context, bool $negated): list<Violation>. For a simple predicate, Assert::callback($subject, fn (mixed $v): bool => ..., 'be a prime number') is usually enough.

Development ​

sh
composer check   # php-cs-fixer, PHPStan (level max + strict rules), PHPUnit, Infection
composer cs:fix
composer coverage

The codebase is kept at 100% line coverage and 100% mutation score (MSI).


From the README.md of EugeneErg/Assert · composer require eugene-erg/assert