eappointment / mellon
参数验证器和验证辅助工具
v2.07.05
2024-08-29 07:28 UTC
Requires
- php: >=7.3.0
- ext-json: >=0
- ext-pcre: >=0
- psr/http-message: >=0
Requires (Dev)
- phpmd/phpmd: ^2.8.0
- phpunit/phpunit: ^9.5.4
- squizlabs/php_codesniffer: *
This package is auto-updated.
Last update: 2024-08-29 07:55:12 UTC
README
链接到主仓库: https://gitlab.com/eappointment/mellon/
Mellon 是一个使用 PHP 提供的 filter-functions 的验证库。它为没有自带的验证库的 PHP 微型框架编写。
'Speak, friend, and enter'
使用方法
在纯 PHP 中,简单的验证可能看起来像这样
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
使用 Mellon,看起来像这样
$validator = new \BO\Mellon\Validator($_GET);
$name = $validator->getParameter('name')->isString()->getValue();
使用所有 $_REQUEST 变量的快捷方式,你可以这样使用
use \BO\Mellon\Validator;
$name = Validator::param('name')
->isString()
->isSmallerThan(32)
->setDefault('John Doe')
->getValue();
为确保没有人在使用你的项目中的超全局变量,请查看 PHP MD 配置文件 中的有争议的规则。
错误消息
Mellon 允许为自定义验证添加错误消息
$size = Validator::param('size')
->isMatchOf('/(px|em|%)/', 'Do include some valid units like px, em or % for a size')
->isFreeOf('/important/', 'The css statement "!important" is not allowed')
->isBiggerThan(2, 'The size should contain some value')
->isSmallerThan(10, 'You should enter a size, no short story expected')
->setDefault('100%');
if ($size->hasFailed()) {
throw new Exception("Error in size param: " . implode(';', $size->getMessages()));
}
else {
echo $size->getValue();
}
对于在模板引擎中使用验证,Mellon 支持数组输出
$sizeParam = $size->getStatus();
/**
* Contains the following keys:
* failed - True if validation has failed
* messages - A list of error messages in case the validation has failed
* value - Value, might be the default value if validation has failed
*/