Conditions
optional
optional($ref, $rule) passes when the key is missing. When the key is present, the rule must hold, even if the value is null:
php
$age = Assert::optional(Assert::ref('age'), Assert::isInteger(Assert::ref('age')));
$age->validate([]); // true
$age->validate(['age' => 5]); // true
$age->validate(['age' => null]); // false: age must be of type int, null givenTo let null through as well, wrap the rule: Assert::any(Assert::isNull(...), ...).
when
when($condition, $then, $else = null) uses the condition only to choose a branch:
php
$vat = Assert::when(
Assert::equal(Assert::ref('type'), 'company'),
Assert::isString(Assert::ref('vat')), // companies need a VAT number
Assert::isNull(Assert::ref('vat')), // nobody else may have one
);
$vat->violations(['type' => 'company']); // vat must be of type string, null given
$vat->violations(['type' => 'person', 'vat' => 'DE1']); // vat must be of type null, string givenThe condition's own failures are never reported, and not() does not negate the condition. Without $else, a failed condition means the rule holds.
optional($ref, $rule) is exactly when(exists($ref), $rule).
Under not()
not(when(c, t, e)) negates the branch that was chosen. Without $else, a failed condition is reported instead, because "c and not t" needs c:
php
Assert::not(Assert::optional(Assert::ref('age'), Assert::isInteger(Assert::ref('age'))))->violations([]);
// age must exist