Skip to content

Operands and references ​

Every argument of a rule is an operand: either a literal, or an expression that reads the validated data.

ExpressionMeansLabel in messages
5, 'abc', [1, 2]a literal5, "abc", [1, 2]
Assert::value()the value being checkedvalue
Assert::ref('a', 'b')$value['a']['b']a.b
Assert::parent(2, 'max')two levels up, then ['max']max
Assert::length($x)characters in a string (not bytes)length of name
Assert::count($x)elements of an array or a Countablecount of lines

Paths ​

ref() steps into arrays, ArrayAccess objects and public properties of objects. String keys are joined with dots and integer keys are written in brackets: items[1].qty.

php
Assert::isInteger(Assert::ref('items', 1, 'qty'))->violations($data);
// items[1].qty must be of type int, string given

Missing keys ​

A missing key, or a key under a missing one, resolves to null, so a type rule reports it naturally:

php
Assert::isInteger(Assert::ref('x'))->violations([]);  // x must be of type int, null given

To tell "missing" from "null", use exists:

php
Assert::exists(Assert::ref('id'))->validate(['id' => null]);  // true
Assert::exists(Assert::ref('id'))->validate([]);              // false: "id must exist"

To check a key only when it is present, use optional.

Inside each and some ​

In each() and some(), the rule runs once per element: value() is the element, and parent() is the iterable itself. parent(2, ...) reaches the node that holds the iterable:

php
Assert::each(Assert::ref('lines'), Assert::between(
    Assert::ref('qty'),
    1,
    Assert::parent(2, 'maxQty'),   // lines[i] → lines → the order
));

A reference that goes above the root of the data is a programming error and throws LogicException.

Measures ​

length() and count() turn one value into a number, and then any comparison applies to them:

php
Assert::between(Assert::length(Assert::ref('name')), 1, 100);
Assert::greaterThan(Assert::count(Assert::ref('lines')), 0);

If the value cannot be measured, for example the length of an int, the violation reports the value itself: name must be of type string, int given.