Skip to content

Getting started ​

Install ​

bash
composer require eugene-erg/assert

PHP 8.3+ with ext-mbstring. There are no other dependencies.

The first rule ​

php
use EugeneErg\Assert\Assert;

$signup = Assert::all(
    Assert::key('email')->isString()->matchesRegularExpression('/^[^@\s]+@[^@\s]+$/'),
    Assert::key('password')->isString()->length()->between(8, 64),
    Assert::key('passwordRepeat')->equal(Assert::ref('password')),
    Assert::key('age')->optional()->isInteger()->greaterThanOrEqual(18),
);

Assert::key('email') starts a chain of rules about one key. The rules run in order, and the chain stops at the first one that fails. optional() lets a missing key pass.

Every rule also exists as a static method whose first argument is the subject: Assert::isString(Assert::ref('email')). Use that form to compare fields with each other or to build rules from parts. Both forms mix freely.

Run it ​

A rule can be run three ways:

php
$signup->validate($data);    // bool
$signup->violations($data);  // list<Violation>, empty when the data is valid
$signup->assert($data);      // throws ValidationException when it is not

For ['email' => 'bob', 'password' => '123', 'passwordRepeat' => '124', 'age' => 16], assert() throws an exception with these messages:

email must match "/^[^@\s]+@[^@\s]+$/"
length of password must be greater than or equal to 8 and less than or equal to 64
passwordRepeat must be identical to password
age must be greater than or equal to 18

All failures come back at once, each with its path, code and parameters.

Values you already have ​

Without references, a rule checks literals. This is handy for asserting arguments inside a function:

php
Assert::lessThan($from, $to)->assert();  // "10 must be less than 5" when $from is 10 and $to is 5

Next ​