pklink / validator-chain
在链中执行验证
1.0.0
2016-01-20 20:26 UTC
Requires
- php: >=5.6.0
- pklink/dotor: ~2.0.0
Requires (Dev)
- phpunit/phpunit: ~5.1.0
This package is not auto-updated.
Last update: 2024-09-25 12:14:49 UTC
README
一个库,用于在链中执行多个验证。
安装
使用 Composer 安装 ValidationChain
创建或更新你的 composer.json
{ "require": { "pklink/validation-chain": "0.*" } }
然后运行 Composer
php composer.phar install
最后包括 Composers 自动加载器
include __DIR__ . '/vendor/autoload.php';
基本用法
使用你想要检查的值创建 Chain
的实例
$chain = \Validation\Chain('check me');
现在,在一个链中运行一些测试
$chain ->isString() // return instance of Chain ->isInteger() // return instance of Chain ->isArray() // return instance of Chain ;
如果你想检查所有验证是否运行正常,请使用 isValid
方法
$chain->isValid(); // return false
或者你可以用一条语句这样做
(new \Validation\Chain('check me')) ->isString() ->isInteger() ->isArray() ->isValid()
重置链
使用 reset()
来重置你的链。
$chain = new \Validator\Chain('value'); $chain->isInteger()->isString()->isValid(); // returns false $chain->isValid(); // returns false $chain->isString()->isValid(); // returns false $chain->reset()->isString()->isValid(); // returns true
选项
您可以通过实例化或设置适当的设置器来设置不同的选项。
$chain = new \Validator\Chain('value', ['option' => 'value']);
throwExceptionOnFailure
如果此选项设置为 true
,则 Chain
如果验证失败,将抛出 Validator\Exception
。
默认设置为 false
$chain = new \Validator\Chain('value', ['throwExceptionOnFailure' => true]); try { $chain ->isString() // everything fine ->minimumLengthOf(2) // everything fine ->isArray() // \Validator\Exception will be thrown ->isArray(); // will not perform } catch (\Validator\Excetion $e) { echo 'validation failed!'; }
此选项的设置器为 throwExceptionOnFailure()
$chain->throwExceptionOnFailure(true); $chain->throwExceptionOnFailure(false); $chain->throwExceptionOnFailure(); // set this option to true
stopValidationOnFailure
如果此选项设置为 true
,则 Chain
将不会执行任何进一步的验证。
默认设置为 true
$chain = new \Validator\Chain('value', ['stopValidationOnFailure' => true]); $chain ->isString() // everthing fine ->isArray() // validation fail ->isInteger(); // will not perform
此选项的设置器为 stopValidationOnFailure()
$chain->stopValidationOnFailure(true); $chain->stopValidationOnFailure(false); $chain->stopValidationOnFailure(); // set this option to true
失败监听器
您可以将闭包添加到获取失败通知。
$chain = new \Validator\Chain('value'); $chain->addValidationFailureListener(function() { echo 'failure'; }); $chain->isInteger();
此示例将输出:failure
如果你愿意,你可以在你的监听器中使用失败的 \Validator\Rule
$chain->addValidationFailureListener(function(\Validation\Rule $rule) { echo get_class($rule); });
规则
hasKey()
hasKeys()
isArray()
isInteger()
isInt()
isInteger() 的别名
isNull()
isNull()
isNumeric()
isObject()
isScalar()
isString()
lengthOf( int $length )
maximumLengthOf( int $length )
minumumLengthOf( int $length )
添加你自己的规则
运行测试
您可以从 vendor 文件夹中使用 PHPUnit。
php composer.phar install --dev php vendor/bin/phpunit tests/
或带有代码覆盖率报告
php composer.phar install --dev php vendor/bin/phpunit --coverage-html output tests/
许可
本软件包采用 MIT 许可证授权。有关详细信息,请参阅 LICENSE 文件。