yoshi2889 / validation-closures
用于验证数据的闭包。提供类型验证和其他过滤器。
v0.2
2017-07-22 22:58 UTC
Requires
- php: >=7.1.0
Requires (Dev)
- phpunit/phpunit: ^6.2
This package is auto-updated.
Last update: 2024-08-27 02:57:30 UTC
README
用于验证数据的闭包。提供类型验证和其他过滤器。
安装
您可以通过 composer
安装此类
composer require yoshi2889/validation-closures
用法
所有闭包都作为公共静态方法公开。例如,要使用 Types\string() 闭包
$closure = \ValidationClosures\Types::string(); $is_string = $closure('This is a string'); // True echo $is_string ? 'True' : 'False';
在以下文档中,除非另有说明,所有方法都返回布尔值类型。
范围
Ranges 类包含用于检查值是否在范围内的方法。它包含以下方法
stringWithLengthBetween(int $minimumLength, int $maximumLength)
:测试给定的字符串长度是否在$minimumLength <= length <= $maximumLength
范围内intBetween(int $minimum, int $maximum)
:测试给定的 int 是否在$minimum <= int <= $maximum
范围内intBetweenExclusive(int $minimum, int $maximum)
:测试给定的 int 是否在$minimum < int < $maximum
范围内floatBetween(float $minimum, float $maximum)
:与intBetween
相同,但测试浮点数。floatBetweenExclusive(float $minimum, float $maximum)
:与intBetweenExclusive
相同,但测试浮点数。enum(...$allowedValues)
:测试给定的值是否存在于$allowedValues
中,类似于其他语言中的 Enum 类型。typeEnum(...$allowedTypes)
:测试给定的值是否属于$allowedTypes
中的类型。stringOneOf(...$allowedValues)
:测试给定的字符串是否存在于$allowedValues
中。
反射
Reflection 类允许您从 PHP 的 ReflectionClass 中找到的所有方法创建闭包。它最适用于 is*
方法。例如,要创建 implementsInterface 方法的闭包
$closure = Reflection::implementsInterface(stdClass::class);
Reflection 类将自动处理 ReflectionClass
对象的实例化。
类型
Types 类包含用于类型验证的方法。它包含以下方法
string()
:测试给定的值是否为字符串。int()
:测试给定的值是否为整数。float()
:测试给定的值是否为浮点数。boolean()
:测试给定的值是否为布尔值。array()
:测试给定的值是否为数组。callable()
:测试给定的值是否为可调用的函数/方法。object()
:测试给定的值是否为已实例化的对象。numeric()
:测试给定的值是否为数值。有关详细信息,请参阅 PHP 手册中的 is_numeric。instanceof(string $class)
:测试给定的值是否为给定类的实例。
工具
Utils 类包含用于操作闭包的方法。它包含以下方法
invert(\Closure $closure): \Closure
:反转闭包。例如,反转 Types::string() 会通过所有不是字符串的值。merge(\Closure $closure1, \Closure $closure2): \Closure
:合并两个闭包。结果闭包将返回 true,如果 任一 闭包或两个闭包都解析为 true。both(\Closure $closure1, \Closure $closure2): \Closure
:合并两个闭包。结果闭包只有在 两个 闭包都解析为 true 时才返回 true。validateArray(Closure $closure, array $values): bool
:检查给定数组中的所有值是否通过给定的闭包验证。如果1个或多个值未通过验证,则返回false;如果所有元素都通过验证,则返回true。
许可证
此代码在MIT许可证下发布。请参阅LICENSE
以阅读许可证内容。