joebengalen/assert

1.0.0 2015-08-28 11:58 UTC

This package is not auto-updated.

Last update: 2024-09-14 16:55:40 UTC


README

Build Status Coverage Status SensioLabsInsight Total Downloads License

众所周知,当我们使用现有的库时,我们希望某些事情可以有所不同。为了确保我可以用断言的方式使用最适合自己的方法,我创建了自定义的实现。

断言方法旨在用于检查传入的参数是否符合预期。如果变量不满足断言,将抛出 InvalidArgumentException 异常。

由于在PHPDoc中的类中,虚拟断言与netbeans中的静态方法不兼容,因此我需要将所有可用的断言都作为实际方法而不是虚拟方法。

安装

通过 Composer

$ composer require joebengalen/assert

用法

use JoeBengalen\Assert\Assert;

/**
 * @param int  $arg1
 * @param bool $arg2
 */
function foo($arg1, $arg2)
{
    // Make sure the arguments are indeed what they should be
    Assert::isInteger($arg1);
    Assert::isBoolean($arg2);

    // Actual code ...
}

// This will be fine ...
foo(12, true);

// ... but this will throw an InvalidArgumentException
foo(2, 4);

自定义异常消息

有时你可能想使用不同的消息抛出异常。这可以通过将第二个字符串参数传递给断言方法来实现。

错误消息将通过 sprintf() 运行,其中传递的变量将转换为一个有用的字符串,并将可用。

Assert::isBoolean(3, 'Custom message: got %s, but expected boolean');
// Throws: "Custom message: got integer, but expected boolean"

一些断言方法需要额外的参数,这些参数对于断言是必需的。自定义消息始终是最后一个参数。额外的参数也将按参数顺序传递给 sprintf()。这意味着要断言的值将是传递给 sprintf() 的第一个字符串。

Assert::isInstanceOf(new Foo, 'Bar', 'Custom message: got %s, but expected instance of %s');
// Throws: "Custom message: got Foo, but expected instance of Bar"

如果你想以不同的顺序在消息中使用参数,可以通过引用它们的编号来交换它们。

Assert::isInstanceOf(new Foo, 'Bar', 'Custom message: expected instance of %2$s, but got %s');
// Throws: "Custom message: expected instance of Bar, but got Foo"

有关交换参数的更多信息,请参阅 sprintf() 的php文档。

变更日志

请参阅 CHANGELOG 了解最近更改的信息。

测试

此项目使用 PHPUnit 进行测试。PHPUnit 不是必需的依赖项,因此必须手动安装 phpunit 才能运行测试。这样做的原因是我更喜欢将 phpunit 全局安装。