Assertion Library for PHP
Published on by Paul Redmond
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:
<?phpuse 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'); // successAssertion::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.