moccalotto/valit

使用自文档代码在运行时验证HTTP请求、输入数据和方法参数

2.1.1 2018-12-26 09:25 UTC

README

Travis Build Status PHP Versions Latest Stable Version License

使用流畅的语法验证变量。

安装

在您的终端中执行以下Composer命令

composer require moccalotto/valit

用法

Ensure::that($age)
    ->isNumeric()
    ->isGreaterThanOrEqual(18)
    ->isLowerThanOrEqual(75);

上面的例子使用Valit\Ensure外观来验证一个变量。如果任何断言失败,将抛出Valit\Exceptions\InvalidValueException异常。

验证值

如果您不想抛出异常,请使用Check外观。

您可以使用throwExceptionIfNotSuccessful方法在断言失败时抛出异常。这种方法的优点是抛出的异常将包含所有失败的断言,而不仅仅是第一个。

use Valit\Check;

$age = 42; // the variable to validate

$validation = Check::that($age)
    ->isInt()                   // Success
    ->isGreaterThanOrEqual(42)  // Success
    ->isLessThan(100);          // Success

$validation->throwExceptionIfNotSuccessful();

// no exception cast, we continue

另请参阅

验证容器

您可以使用结构化和明确的方式轻松测试整个数组,例如提交的字段或JSON响应,如下面的例子所示

$checks = Check::that($input)->contains([
    'name'      => 'string & shorterThan(100)',
    'email'     => 'email & shorterThan(255)',
    'address'   => 'string',
    'age'       => 'naturalNumber & greaterThanOrEqual(18) & lowerThanOrEqual(100)',

    'orderLines'                => 'conventionalArray',
    'orderLines/*'              => 'associative',
    'orderLines/*/productId'    => 'uuid',
    'orderLines/*/count'        => 'integer & greaterThan(0)',
    'orderLines/*/comments'     => 'optional & string & shorterThan(1024)',
]);

如您所见,通过”/“字符检查嵌套数据。

您可以如此获取单个字段的错误消息

// get the errors associated with the top level field 'age'.
$errors = $checks->errorMessagesByPath('age');

// get the errors for the productId of the first orderLine.
$errors = $checks->errorMessagesByPath('orderLines/0/productId');

// get the error associated with the second orderLine
$errors = $checks->errorMessagesByPath('orderLines/1');

实用工具

Valit提供了Val外观,允许快速进行类型转换和断言。

以下是一些测试变量是否是可迭代的方法,与您的PHP版本无关。

use Valit\Util\Val;

if (!Val::is($container, 'iterable')) {
    throw new LogicException('$container should be iterable');
}

或者也可以这样

use Valit\Util\Val;

// an InvalidArgumentException will be thrown if $container is not iterable.
Val::mustBe($container, 'iterable');

或者使用您自己的自定义异常

use Valit\Util\Val;

$myException = throw LogicException('$container should be iterable');

// $myException will be thrown if $container is not iterable.
Val::mustBe($container, 'iterable', $myException);

以下是一些您可以进行的类型验证。

代码示例

// single type
Val::mustBe($value, 'callable');

// multiple allowed types via the pipe character
Val::mustBe($value, 'float | int');

// check that $foo is an array of floats
// or an array of integers
Val::mustBe($value, 'float[] | int[]');

// mixing classes, interfaces and basic types.
Val::mustBe($value, 'int|DateTime|DateTimeImmutable');

// multiple types via array notation
Val::mustBe($value, ['object', 'array']);

// a strict array with 0-based numeric index
Val::mustBe($value, 'mixed[]');

// a strict array of strict arrays
Val::mustBe($value, 'mixed[][]');