nuonzion / php-expect
一个轻量级且表达性强的库,用于验证前置条件和不变性。
Requires
- php: >=5.3.0
This package is auto-updated.
Last update: 2024-09-09 00:54:27 UTC
README
PHP Expect 是一个轻量级的断言库,用于验证 PHP 中的参数和不变性。
安装
您可以使用 Composer 下载和安装 PHP Expect。要将 PHP Expect 添加到您的项目中,只需在项目中的 composer.json
文件中添加对 nuonzion/php-expect 的依赖项。
以下是一个定义 PHP Expect 依赖项的示例 composer.json
文件
{
"require": {
"nunzion/php-expect": "~1.0"
}
}
用法
对于大型项目,建议从 Expect
类派生以将依赖项集中到 Nunzion\Expect
。
<?php
namespace MyCompany\MyApplication;
class Expect extends \Nunzion\Expect
{
//If you need custom validations, you can define them here.
}
//Later you can call:
\MyCompany\MyApplication\Expect::that(3)->isBetween(1, 4);
//Instead of \Nunzion\Expect::that(3)->isBetween(1, 4);
支持的测试
<?php
use MyCompany\MyApplication\Expect;
Expect::that(null)->isNull();
Expect::that(0)->isNotNull(); // 0 !== null, so 0 is not null.
Expect::that("")->isEmpty();
Expect::that(2)->isNotEmpty();
Expect::that("foo")->equals("foo"); //"foo" == "foo"
Expect::that(1)->isTheSameAs(1); //1 === 1
Expect::that("bar")->isString();
Expect::that(4)->isInt();
Expect::that(new Foo())->isObject();
Expect::that("file_exists")->isCallable();
Expect::that(array(1, 2))->isArray();
Expect::that($a)->isTypeOf("\FooInterface");
//Chaining is possible too
Expect::that(1)->isBetween(0, 2)
->isGreaterThan(0)
->isLessThan(2)
->isGreaterThanOrEqualTo(1)
->isLessThanOrEqualTo(1);
$arr = array("bla" => 2, "foo" => null);
Expect::that($arr)->itsArrayElement("bla")->isDefined();
Expect::that($arr)->itsArrayElement("bla")->isInt();
Expect::that($arr)->itsArrayElement("blubb")->isUndefinedOrInt();
Expect::that($arr)->itsArrayElement("foo")->isNullOrInt();
$result = myTest($a); //Some custom test.
if ($result != null)
{
//Will throw an \UnexpectedValueException with message:
//"The value must be valid, the test returned: " + $result.
Expect::that(null)->_("must be valid, the test returned: {testResult}",
array("testResult" => $result));
//The value for the placeholder 'testResult' will be available within
//the exception and could be used by loggers.
}
代码示例
<?php
use Nunzion\Expect;
class Square
{
private $a;
private $b;
public function __construct($length)
{
//throws \InvalidArgumentException,
//because "length" is a parameter of Square::__construct
Expect::that($length)->isGreaterThan(0);
$this->a = $length;
$this->b = $length;
}
public function getArea()
{
//throws Nunzion\InvariantException,
//because "b" is a member of Square
Expect::that($this->b)->equals($this->a);
return $this->a * $this->b;
}
public function setData($data)
{
//Expects data is array and has a key 'length'
//which is int and greater than 0
Expect::that($data)->itsArrayElement("length")->isGreaterThan(0);
$this->a = $data["length"];
$this->b = $this->a;
}
}
new Square(-1);
前置条件、不变性和正常条件
PHP Expect 区分前置条件、不变性和正常条件。
前置条件验证参数 - 无效参数可能由调用者代码中的错误或不良用户输入引起。如果条件失败且要检查的值是参数(that()
内的表达式),PHP Expect 将自动抛出 \InvalidArgumentException
。
不变性是确保对象状态始终有效的条件。如果要检查的值是 $this
的成员,PHP Expect 将识别此类条件,如果条件失败则抛出 Nunzion\InvariantViolationException
。通常,这些异常是由错误引起的,因此应该记录这些异常。
正常条件是 PHP Expect 不识别的所有条件。
isNullOr 和 isUndefinedOr
您可以在每个 is* 方法调用之前添加 isNullOr
和 isUndefinedOr
。如果要测试的值是 null
或 undefined
,则测试将成功。
扩展 Nunzion\Expect
您可以通过覆盖 get*ExceptionConstructor
方法来扩展 Nunzion\Expect 以自定义要抛出的异常。这可以通过覆盖这些方法来实现。
<?php
namespace MyCompany;
class Expect extends Nunzion\Expect
{
protected function getPreconditionViolationExceptionConstructor(
$message, $arguments)
{
print_r($arguments); //arguments contains additional information
//Return the exception construct information you want to throw instead.
//Delaying the construction of the exception will prevent its stack trace
//to contain too much PHP Expect methods.
return array(
//the method which will be called to create the exception.
array(new \ReflectionClass(
"\MyNamespace\MyInvariantViolationException"), "newInstance"),
//the arguments which will be passed to the method.
array($message)
);
}
protected function getInvariantViolationExceptionConstructor(
$message, $arguments)
{
print_r($arguments);
return parent::getInvariantViolationExceptionConstructor(
$message, $arguments);
}
protected function getConditionViolationExceptionConstructor(
$message, $arguments)
{
print_r($arguments);
return parent::getConditionViolationExceptionConstructor(
$message, $arguments);
}
}
作者
Henning Dieterichs - henning.dieterichs@hediet.de
许可协议
PHP Expect 在 MIT 许可协议下授权。