stiggg/asserter

Asserter library

v0.3 2014-07-20 20:25 UTC

README

"Use assertions to document assumptions made in the code and to flush out unexpected conditions." --Steve McConnell

This library allows to create and manage generic assertations, that can be reused in your code. You can use the Asserter component as a service, or create quick assertations by calling static methods.

Asserter component can be coupled with PSR-3 compatible logger to log assertation failures before throwing AssertException.

Usage

<?php
    use Stiggg\Asserter\Asserter;
    
    ...
    $message = sprintf('number %s was not a prime', $number);

    # use the service to register assertion...
    $asserter = new Asserter($logger);  // logger is optional
    $asserter->register('numberIsPrime', function($num) {
        // http://icdif.com/computing/2011/09/15/check-number-prime-number/
        if($num == 1) return false;
        if($num == 2) return true;
        if($num % 2 == 0) return false;
        for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
            if($num % $i == 0) return false;
        }
        return true;
    }, $message);
    
    $asserter->assert('numberIsPrime', array(8));

    # ...or call the component directly
    Asserter::callback(function($num) {
        if($num == 1) return false;
        if($num == 2) return true;
        if($num % 2 == 0) return false;
        for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
            if($num % $i == 0) return false;
        }
        return true;
     }, array(8), $message);

There's two assertation types for static access, "callback" or "true". Specific assertation methods (like for integer, regexp etc.) are easy to do with "true" assertation:

<?php
    $number = 2;
    Asserter::true(is_numeric($number), $number . ' was not numeric');

    $regexp = '/assert/';
    $haystack = 'assertations are cool';
    Asserter::true(preg_match($regexp, $haystack), sprintf('"%s" did not match regexp "%s"', $haystack, $regexp));

Licence

MIT

Versioning

Versioning supports semver: http://semver.org/

See packagist for version details: https://packagist.org/packages/stiggg/asserter