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

Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Voxie
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Remote
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.
Senior Full Stack Developer (PHP | Vue | DDD)
Charleston, SC
MassageBook