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('/@/'), withoptional(),nullable(),length()andcount(). - 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
minwithmax, or an item with a limit two levels up. - Negation done once, correctly.
not()flips any rule, includingall,any,eachandsome(by De Morgan's laws). Type preconditions are never negated:not(lessThan(x, 5))still rejectsnull. - Structured violations. Every failure carries
code,path,message,parametersandnegated, so you can localize it or return it from an API.
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:
$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
| Expression | Means |
|---|---|
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:
Assert::lessThan($from, $to)->assert();Rules
| Group | Rules |
|---|---|
| Chains | key, that |
| Logic | all, any, not, each, some, when, optional |
| Presence | exists |
| Types | type($x, 'int|string'), isString, isInteger, isFloat, isBool, isNull, isArray, isObject, isIterable, isCallable, isNumeric, instanceOf |
| Classes | isA, isSubclassOf (class names are accepted only with allowString: true) |
| Values | equal (strict by default), in, empty, callback |
| Comparison | lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual, between |
| Strings | matchesRegularExpression, 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
// 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.negatedistruewhen it was checked throughnot(). 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 inalternatives.some: an iterable had no elements to satisfysome(ornot(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
composer check # php-cs-fixer, PHPStan (level max + strict rules), PHPUnit, Infection
composer cs:fix
composer coverageThe codebase is kept at 100% line coverage and 100% mutation score (MSI).
From the README.md of EugeneErg/Assert · composer require eugene-erg/assert