dgame/php-ensurance

php ensurance

v2.3.0 2021-07-04 19:23 UTC

This package is auto-updated.

Last update: 2024-04-05 00:51:19 UTC


README

CircleCI Scrutinizer Code Quality Code Coverage Build Status StyleCI

design by contract for PHP

If your check fails, an Exception is thrown

Strings

equality

ensure('foo')->isString()->isEqualTo('foo');
ensure('foo')->isString()->isNotEqualTo('bar');

pattern

ensure('test@foo')->isString()->matches('#^[a-z]+@\w{3}$#i');
ensure('FooBar')->isString()->beginsWith('Fo');
ensure('FooBar')->isString()->endsWith('ar');

size

ensure('foo')->isString()->hasLengthOf(3);
ensure('foo')->isString()->isShorterThan(4);
ensure('foo')->isString()->isLongerThan(2);

and more

Numerics

type check

ensure(42)->isInt();
ensure('42')->isInt();

ensure(4.2)->isFloat();
ensure('4.2')->isFloat();

value check

ensure(42)->isNumeric()->isGreaterThan(23);
ensure(23)->isNumeric()->isLessThan(42);
ensure(42)->isEqualTo(42);

positive / negative

foreach (range(0, 100) as $n) {
    ensure($n)->isPositive();
}
foreach (range(-1, -100) as $n) {
    ensure($n)->isNegative();
}

even / odd

for ($i = 0; $i < 42; $i += 2) {
    ensure($i)->isEven();
}
for ($i = 1; $i < 42; $i += 2) {
    ensure($i)->isOdd();
}

between range

ensure(2)->isNumeric()->isBetween(1, 3);

array

check for a key

ensure(['a' => 'b'])->isArray()->hasKey('a');

check for a value

ensure(['a', 'b'])->isArray()->hasValue('a');

check length

ensure([])->isArray()->hasLengthOf(0);
ensure(range(0, 99))->isArray()->hasLengthOf(100);
ensure([1, 2, 3])->isArray()->isShorterThan(4);
ensure([1, 2, 3])->isArray()->isLongerThan(2);

check if associativ or not

ensure(['a' => 'b'])->isArray()->isAssociative();

ensure not empty / not null

ensure('')->isNotNull()->isNotEmpty();

ensure identity (===) / equality (==)

ensure(42)->isEqualTo('42');
ensure(42)->isIdenticalTo(42);

bool

is true / false

ensure((2 * 3) === (3 * 2))->isTrue();
ensure((2 * 3) === (3 * 3))->isFalse();

You can also specify your own Exception messages:

ensure(1 === 1)->isTrue()->orThrow('You will never see this error');

Enforcement

If you want to enforce that some condition is true, use enforce:

enforce(true)->orThrow('That is not true...');

If you don't specify a Throwable, an AssertionError will be used:

enforce(0); // throws AssertionError

Expectations

Bind expectations to your values and offer default values if the expectation don't apply. You can either use else or then to evaluate if an Throwable was thrown. The usage of else or then will disregard and invalidate the Throwable internally:

$this->assertEquals('foo', ensure(42)->isEven()->then('foo'));
$this->assertEquals(23, ensure(42)->isOdd()->else(23));

also you can use either ... or to set values for both outcomes:

$this->assertTrue(ensure(42)->isOdd()->either(false)->or(true));
$this->assertFalse(ensure(23)->isOdd()->either(false)->or(true));