hanneskod / clean

一个简单的(即简单的)数据清理工具(即验证工具)

3.0.0 2020-01-01 01:05 UTC

This package is auto-updated.

Last update: 2024-08-26 07:48:16 UTC


README

Packagist Version Build Status Quality Score

一个简单的(即简单的)数据清理工具(即验证工具)

为什么?

有时执行复杂的输入验证是必要的,为此存在许多工具(例如 Respect\Validation)。在其他时候(可以说是大多数时候),内置的 PHP 函数,如 ctype-family 和正则表达式,就足够好了。在这些时候,引入一个重型的验证库来执行基本任务可能会变得过于复杂。

Clean 在调用者和原生 PHP 函数周围充当了一个薄薄的包装器,少于 100 行逻辑代码,并允许您通过简单紧凑的流畅接口过滤和验证用户输入。

安装

composer require hanneskod/clean

Clean 需要 PHP 7.4 或更高版本,并且没有用户空间依赖。

使用方法

基本用法包括在一个 ArrayValidator 中分组一组 规则

use hanneskod\clean\ArrayValidator;
use hanneskod\clean\Rule;

$validator = new ArrayValidator([
    'foo' => (new Rule)->match('ctype_digit'),
    'bar' => (new Rule)->match('ctype_alpha'),
]);

$tainted = [
    'foo' => 'not-valid only digits allowed',
    'bar' => 'valid'
];

try {
    $validator->validate($tainted);
} catch (Exception $e) {
    echo $e->getMessage();
}

定义规则

规则使用 pre()match()post() 方法定义。

  1. pre() 可以接受任意数量的 callable 参数作为预匹配过滤器。过滤器接受一个参数,并以过滤后的状态返回它。
  2. post() 可以接受任意数量的 callable 参数作为后匹配过滤器。过滤器接受一个参数,并以过滤后的状态返回它。
  3. match() 可以接受任意数量的 callable 参数作为验证器。该可调用函数应接受一个参数,如果参数有效则返回 true,否则返回 false。

一个规则定义可能看起来像这样

use hanneskod\clean\Rule;

$rule = (new Rule)->pre('trim')->match('ctype_alpha')->post('strtoupper');

// outputs FOOBAR
echo $rule->validate('   foobar   ');

使用正则表达式匹配器

Rule 验证器包含一个特殊的匹配器:regexp(),用于将字符串输入与 POSIX 风格的正则表达式(preg_match())进行匹配。

use hanneskod\clean\Rule;

$rule = (new Rule)->regexp('/A/');

// outputs ABC
echo $rule->validate('ABC');

使输入可选

规则可以使用 def() 方法定义默认值。默认值用作 null 的替代品。这实际上使得在 ArrayValidator 设置中字段可选。

use hanneskod\clean\ArrayValidator;
use hanneskod\clean\Rule;

$validator = new ArrayValidator([
    'key' => (new Rule)->def('baz')
]);

$data = $validator->validate([]);

// outputs baz
echo $data['key'];

指定自定义异常消息

当验证失败时,会抛出一个带有描述错误的通用消息的异常。每个规则都可以使用 msg() 方法定义自定义异常消息,以微调此行为。

use hanneskod\clean\Rule;

$rule = (new Rule)->msg('Expecting numerical input')->match('ctype_digit');

try {
    $rule->validate('foo');
} catch (Exception $e) {
    // outputs Expecting numerical input
    echo $e->getMessage();
}

忽略未知输入项

默认情况下,未知输入项会触发异常。

use hanneskod\clean\ArrayValidator;

$validator = new ArrayValidator([]);

// throws a clean\Exception as key is not present in validator
$validator->validate(['this-key-is-not-definied' => '']);

使用 ignoreUnknown() 关闭此功能。

use hanneskod\clean\ArrayValidator;

$validator = (new ArrayValidator)->ignoreUnknown();

$clean = $validator->validate(['this-key-is-not-definied' => 'foobar']);

// outputs empty
echo empty($clean) ? 'empty' : 'not empty';

嵌套验证器

ArrayValidators 可以按以下方式嵌套

use hanneskod\clean\ArrayValidator;
use hanneskod\clean\Rule;

$validator = new ArrayValidator([
    'nested' => new ArrayValidator([
        'foo' => new Rule
    ])
]);

$tainted = [
    'nested' => [
        'foo' => 'bar'
    ]
];

$clean = $validator->validate($tainted);

//outputs bar
echo $clean['nested']['foo'];

使用 applyTo() 检查验证结果

validate() 方法在匹配失败时立即抛出异常。当然,这可能不是你想要的。你可以通过使用 applyTo() 方法直接检查验证结果。

use hanneskod\clean\Rule;

$rule = (new Rule)->match('ctype_digit');

$result = $rule->applyTo('12345');

$result->isValid() == true;

// outputs 12345
echo $result->getValidData();

捕获所有失败

可以使用结果对象访问单个错误。

use hanneskod\clean\ArrayValidator;
use hanneskod\clean\Rule;

$validator = new ArrayValidator([
    '1' => (new Rule)->match('ctype_digit')->msg('failure 1'),
    '2' => (new Rule)->match('ctype_digit')->msg('failure 2'),
]);

// Both 1 and 2 will fail as they are not numerical
$result = $validator->applyTo(['1' => '', '2' => '']);

//outputs failure 1failure 2
foreach ($result->getErrors() as $errorMsg) {
    echo $errorMsg;
}

识别失败的规则

use hanneskod\clean\ArrayValidator;
use hanneskod\clean\Rule;

$validator = new ArrayValidator([
    'foo' => (new Rule)->match('ctype_digit'),
    'bar' => (new Rule)->match('ctype_digit'),
]);

$result = $validator->applyTo([
    'foo' => 'not-valid',
    'bar' => '12345'
]);

// outputs foo
echo implode(array_keys($result->getErrors()));

实现自定义验证器

use hanneskod\clean\AbstractValidator;
use hanneskod\clean\Rule;
use hanneskod\clean\ValidatorInterface;

class NumberRule extends AbstractValidator
{
    protected function create(): ValidatorInterface
    {
        return (new Rule)->match('ctype_digit');
    }
}

// Outputs 1234
echo (new NumberRule)->validate('1234');