Skip to content

Getting Started

Assert is a comprehensive assertion library for PHP 8.4+ that enables robust validation and preconditions throughout your code.

Terminal window
composer require cline/assert

The library provides four main ways to perform assertions:

Use Assertion class directly for immediate validation:

use Cline\Assert\Assertions\Assertion;
Assertion::string($value);
Assertion::notEmpty($value);
Assertion::minLength($value, 3);

Use Assert::that() for fluent, chainable assertions:

use Cline\Assert\Assert;
Assert::that($email)
->notEmpty()
->email();
Assert::that($password)
->string()
->minLength(8)
->maxLength(100);

Use expect() for test-friendly, chainable expectations:

use function Cline\Assert\expect;
expect($value)->toBeString();
expect($count)->toBeInt();
expect($result)->toBe(42);
expect($items)->toHaveCount(3);
expect($value)->not->toBeNull();

Collect multiple validation errors before throwing:

use Cline\Assert\Assert;
Assert::lazy()
->that($email, 'email')->email()
->that($age, 'age')->integer()->min(18)
->that($name, 'name')->notEmpty()->minLength(2)
->verifyNow(); // Throws exception with all errors

All assertions throw AssertionFailedException when validation fails:

use Cline\Assert\Assertions\Assertion;
use Cline\Assert\Exceptions\AssertionFailedException;
try {
Assertion::integer($value);
} catch (AssertionFailedException $e) {
echo $e->getMessage();
echo $e->getPropertyPath();
echo $e->getValue();
echo $e->getConstraints();
}

All assertions accept optional custom error messages:

Assertion::notEmpty($username, 'Username is required');
Assertion::email($email, 'Please provide a valid email address');
Assert::that($age)
->integer('Age must be a number')
->min(18, 'You must be at least 18 years old');

Custom messages support sprintf-style placeholders:

Assertion::minLength($username, 3, 'Username must be at least %2$s characters. Got: %s');
// => "Username must be at least 3 characters. Got: ab"
Assertion::range($age, 18, 65, 'Age must be between %2$s and %3$s. Got: %s');
// => "Age must be between 18 and 65. Got: 17"

Use property paths to identify which field failed validation:

Assertion::string($user->email, null, 'user.email');
Assert::that($user->email, null, 'user.email')
->notEmpty()
->email();