If your check fails, an Exception is thrown
ensure('foo')->isString()->isEqualTo('foo');
ensure('foo')->isString()->isNotEqualTo('bar');
ensure('test@foo')->isString()->matches('#^[a-z]+@\w{3}$#i');
ensure('FooBar')->isString()->beginsWith('Fo');
ensure('FooBar')->isString()->endsWith('ar');
ensure('foo')->isString()->hasLengthOf(3);
ensure('foo')->isString()->isShorterThan(4);
ensure('foo')->isString()->isLongerThan(2);
and more
ensure(42)->isInt();
ensure('42')->isInt();
ensure(4.2)->isFloat();
ensure('4.2')->isFloat();
ensure(42)->isNumeric()->isGreaterThan(23);
ensure(23)->isNumeric()->isLessThan(42);
ensure(42)->isEqualTo(42);
foreach (range(0, 100) as $n) {
ensure($n)->isPositive();
}
foreach (range(-1, -100) as $n) {
ensure($n)->isNegative();
}
for ($i = 0; $i < 42; $i += 2) {
ensure($i)->isEven();
}
for ($i = 1; $i < 42; $i += 2) {
ensure($i)->isOdd();
}
ensure(2)->isNumeric()->isBetween(1, 3);
ensure(['a' => 'b'])->isArray()->hasKey('a');
ensure(['a', 'b'])->isArray()->hasValue('a');
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);
ensure(['a' => 'b'])->isArray()->isAssociative();
ensure('')->isNotNull()->isNotEmpty();
ensure(42)->isEqualTo('42');
ensure(42)->isIdenticalTo(42);
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');
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
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));