Recipes
An order with lines
php
$order = Assert::key('lines')->isArray()->count()->greaterThan(0)->each(Assert::all(
Assert::key('sku')->isString(),
Assert::key('qty')->between(1, Assert::parent(2, 'maxQty')),
));
$order->violations(['maxQty' => 10, 'lines' => [['sku' => 'A', 'qty' => 2], ['sku' => 5, 'qty' => 11]]]);
// lines[1].sku must be of type string, int given
// lines[1].qty must be greater than or equal to 1 and less than or equal to maxQtyA date range
Dates compare with dates:
php
$period = Assert::all(
Assert::instanceOf(Assert::ref('from'), DateTimeInterface::class),
Assert::instanceOf(Assert::ref('to'), DateTimeInterface::class),
Assert::lessThanOrEqual(Assert::ref('from'), Assert::ref('to')),
);
// from must be less than or equal to toA status from a list
php
Assert::key('status')->in(['draft', 'published']);
// status must be one of ["draft", "published"]With a backed enum, check the value against its cases: Assert::in(Assert::ref('status'), array_column(Status::cases(), 'value')).
A partial update
In a PATCH, every field is optional, but a field that is sent must be valid:
php
$patch = Assert::all(
Assert::key('name')->optional()->isString()->length()->between(1, 100),
Assert::key('email')->optional()->isString()->matchesRegularExpression('/^[^@\s]+@[^@\s]+$/'),
);At least one admin
php
Assert::key('roles')->some(Assert::that(Assert::value())->equal('admin'));Arguments of a function
Rules work on literals too, so they also serve as guard clauses:
php
function transfer(int $amount, int $balance): void
{
Assert::between($amount, 1, $balance)->assert();
// ...
}Reusing rules
Rules are immutable, so build them once:
php
final class Rules
{
public static function money(Ref $field): Rule
{
return Assert::all(Assert::isInteger($field), Assert::greaterThanOrEqual($field, 0));
}
}
Assert::each(Assert::ref('prices'), Rules::money(Assert::value()));