Assertion Library for PHP


June 27th, 2019

Assertion Library for PHP

Assert is a composer package by Benjamin Eberlei which serves as a “thin assertion library for input validation in business models.”

Idea is to reduce the amount of code for implementing assertions in your model and also simplify the code paths to implement assertions. When assertions fail, an exception is thrown, removing the necessity for if-clauses in your code.

Here’s a basic example usage from the README:

use Assert\Assertion;
function duplicateFile($file, $times)
for ($i = 0; $i < $times; $i++) {
copy($file, $file . $i);

This package has many assertions, including an “all” helper which checks all provided values against a given assertion:

Assertion::isInstanceOf($value, $className);
Assertion::allIsInstanceOf(array(new \stdClass, new \stdClass), 'stdClass'); // success
Assertion::allIsInstanceOf(array(new \stdClass, new \stdClass), 'PDO'); // exception

One thing to note: assertions throw an exception if the assertion fails, thus potentially avoiding conditionals in your code around assertions.

If you need low-level code assertions, this library is packed full of useful assertion methods and strategies like lazy assertions where you may want to collect multiple errors at once instead of failing on the first assertion:

->that(10, 'foo')->string()
->that(null, 'bar')->notEmpty()
->that('string', 'baz')->isArray()

Check out the readme for a full list of available assertions and to learn more about how to use this library in your projects. You can get full installation instructions and view the source code on GitHub at beberlei/assert.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.