adaddinsane / paramverify
参数验证工具
1.4.1
2022-05-02 10:50 UTC
Requires
- php: >=7.2
- ext-mbstring: *
- egulias/email-validator: ^3.1
- riimu/kit-urlparser: ^2.1
Requires (Dev)
- phpunit/phpunit: ^7.0
This package is auto-updated.
Last update: 2024-09-30 01:34:51 UTC
README
这是一个简单的包,用于验证一组数组值,这些值很可能是调用中的参数。有时您可能无法在参数列表中指定它们,可能是因为它们太长,或者因为它们可能在派生类类型之间变化太多。
此类使用一个数组配置,提供了所需的值及其类型。也可以包含非必需值进行检查 - 在这种情况下,只有在它们存在时才会进行检查。
主函数返回一个错误数组。如果它是空的,则表示一切正常。
结构
设置数组看起来像这样
[ 'name' => [ 'required' => true, 'type' => 'string', 'data' => '', 'range' => [] ] ]
'name' 是正在测试的数组中的键值(属性的名称)。
只有 'type' 键是必需的,并且必须是可接受的值之一;如果缺少 'required' 键,则假定其为 false;一些类型需要额外的数据字符串,对于 'regex' 类型,它是正则表达式,对于 'class' 类型,它是完全限定类名,等等。
'range' 键适用于字符串、整数和浮点数,并允许插入长度和范围限制。
如果命名参数在设置数组中但不是“必需的”,如果它缺失,则不会生成错误,但如果它存在,则会进行检查。
类型
完整的类型列表
- any 匹配任何内容
- null 仅匹配 null 值(为了完整性,你永远不知道)
- class 匹配特定的类或接口(在 'data' 中的 FQN)
- object 匹配任何对象
- array 匹配任何数组,数组可以包含它们自己的定义(见后文)。
- int 匹配整数值(并且可以具有范围)
- bool 仅匹配 true 或 false
- int_bool 匹配 true、false、1 和 0
- float 匹配浮点值(并且可以具有范围)
- string 匹配任何字符串(并且可以具有范围)
- string_list 将字符串与固定字符串列表(在 'data' 中用 '|' 分隔)进行匹配。这是一种旧式的 "枚举",也用于验证设置/配置项的类型。
- regex 使用正则表达式(在 'data' 中)测试字符串
- callable 仅匹配可调用的
- resource 仅匹配资源
- url 匹配也是有效 URL 的字符串
- email 匹配也是有效电子邮件地址的字符串
- enum 仅匹配 PHP8.1 枚举(在 'data' 中的 FQN)
如何使用它
$settings = [ 'name' => [ 'required' => true, 'type' => 'string' ], 'value' => [ 'required' => true, 'type' => 'int' 'range' => [ 'min_value' => 1, 'max_value' => 10 ] ] ]; $paramVerifyFactory = new \ParamVerify\ParamVerifyFactory(); // This checks the settings and will throw an exception on error. $verifier = $paramVerifyFactory->make($settings); // Will return an error because 'name' is missing. $parameters = ['value' => 5]; $errors = $verifier->verify($parameters); // Will return no errors. $parameters = ['name' => 'banana', 'value' => 5]; $errors = $verifier->verify($parameters); // Will return an error because value is out of range. $parameters = ['name' => 'banana', 'value' => 15]; $errors = $verifier->verify($parameters); // Will return an error because name is not a string. $parameters = ['name' => ['banana'], 'value' => 15]; $errors = $verifier->verify($parameters);
数组子属性
数组可以有一个额外的属性称为 settings
,它定义了一组子属性。除了资源和它是否真的是一个好主意之外,嵌套没有限制。
$settings = [ 'name' => [ 'required' => true, 'type' => 'string' ], 'address' => [ 'required' => true, 'type' => 'array' 'settings' => [ 'line1' => ['required' => true, 'type' => 'string'], 'line2' => ['type' => 'string'], 'line3' => ['type' => 'string'], 'postal_code' => ['required' => true, 'type' => 'string'], ] ] ]; $paramVerifyFactory = new \ParamVerify\ParamVerifyFactory(); // This checks the settings and will throw an exception on error. $verifier = $paramVerifyFactory->make($settings); // This would not generate any errors. $parameters = [ 'name' => 'jane', 'address' => [ 'line1' => 'first line of address', 'line3' => 'third line of address', 'postal_code' => 'XX1 73YY' ] ]; $errors = $verifier->verify($parameters);