dgame / php-ensurance
php ensurance
v2.3.0
2021-07-04 19:23 UTC
Requires
- php: >=7.1
- ext-curl: *
- ext-dom: *
- ext-json: *
- ext-libxml: *
- dgame/php-type: ^0.13
Requires (Dev)
- phpstan/phpstan: ^0.12
- phpunit/phpunit: >= 8
README
为PHP设计的契约设计
如果您的检查失败,将抛出异常
字符串
等价性
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);
等等
数值
类型检查
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();
确保非空/非null
ensure('')->isNotNull()->isNotEmpty();
确保身份(===
)/等价(==
)
ensure(42)->isEqualTo('42');
ensure(42)->isIdenticalTo(42);
布尔值
是/否
ensure((2 * 3) === (3 * 2))->isTrue(); ensure((2 * 3) === (3 * 3))->isFalse();
您也可以指定自己的异常消息
ensure(1 === 1)->isTrue()->orThrow('You will never see this error');
强制执行
如果您想强制某个条件为真,请使用 enforce
enforce(true)->orThrow('That is not true...');
如果您没有指定可抛出的对象,将使用 AssertionError
enforce(0); // throws AssertionError
期望
将期望绑定到您的值上,并在期望不适用时提供默认值。您可以使用 else
或 then
来评估是否抛出了可抛出对象。使用 else
或 then
将内部忽略并使可抛出对象失效
$this->assertEquals('foo', ensure(42)->isEven()->then('foo')); $this->assertEquals(23, ensure(42)->isOdd()->else(23));
您还可以使用 either ... or
为两种结果设置值
$this->assertTrue(ensure(42)->isOdd()->either(false)->or(true)); $this->assertFalse(ensure(23)->isOdd()->either(false)->or(true));