Skip to content

Chains ​

Most rules are about one field. A chain says them without repeating the field:

php
Assert::key('email')->isString()->matchesRegularExpression('/@/');
Assert::key('name')->isString()->length()->between(1, 100);
Assert::key('note')->optional()->nullable()->isString();

Assert::key(...$path) starts a chain about a key of the value being checked. Assert::that($subject) starts one about anything else: a literal, Assert::value(), or Assert::ref(...).

In order ​

The rules of a chain run in order, and the chain stops at the first one that fails:

php
Assert::key('email')->isString()->matchesRegularExpression('/@/')->violations(['email' => 5]);
// email must be of type string, int given

The pattern is not checked, because a number cannot match it anyway. This is the difference from all(), which reports every failure.

Under not(), a chain means "at least one of its rules does not hold".

Methods ​

Every rule of Assert has a chain method without the subject argument: isString(), between($from, $to), in([...]), equal(Assert::ref('password')), and so on. Chains also have:

MethodDoes
notEmpty()the value must not be empty
exists()the key must be present (a chain on a key only)
each(Rule), some(Rule)the rule must hold for every element or for one; inside, Assert::value() is the element
rule(Rule)any other rule; it sees the same data as the chain

optional and nullable ​

These apply to the whole chain, wherever they stand in it:

MethodPasses when
optional()the key is missing (a chain on a key only)
nullable()the value is null (a missing key reads as null too)
php
$age = Assert::key('age')->optional()->isInteger();

$age->validate([]);              // true
$age->validate(['age' => null]); // false: age must be of type int, null given

length and count ​

length() and count() switch what the rules after them check. Rules before them still check the value:

php
Assert::key('name')->isString()->length()->between(1, 100);
// "name must be of type string, int given" for 5
// "length of name must be greater than or equal to 1 and less than or equal to 100" for ""

Assert::key('tags')->isArray()->count()->lessThanOrEqual(10);

Nested data ​

Chains go inside each(), and parent() reaches out of the element:

php
Assert::key('items')->isArray()->each(Assert::all(
    Assert::key('sku')->exists(),
    Assert::key('qty')->between(1, Assert::parent(2, 'maxQty')),
));
// items[1].qty must be greater than or equal to 1 and less than or equal to maxQty

A chain is a rule, so it also goes into all(), any(), not() and when().