Assertion Library for PHP

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:

<?php
use Assert\Assertion;

function duplicateFile($file, $times)
{
    Assertion::file($file);
    Assertion::digit($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:

Assert::lazy()
    ->that(10, 'foo')->string()
    ->that(null, 'bar')->notEmpty()
    ->that('string', 'baz')->isArray()
    ->verifyNow();

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: News


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

PHP Data Engineer
Remote (US)
FBS
Software Developer
Remote (US & Canada)
Alley
Backend Software Engineer
Remote (UTC +/- 5)
Smartbnb
Programmer
Remote (Overlap w/ Continental US Time Zones)
Tighten
Senior Backend Engineer
Remote
64 Robots
Senior Laravel Developer
Atlanta, GA
Helium LLC
Full-Stack Developer (JS - Vue.js, PHP - Laravel)
US Remote / Telecommute
TTEC Digital