paysera / lib-plugin-data-validation

可迭代输入验证库

0.2.0 2024-03-11 17:20 UTC

This package is auto-updated.

Last update: 2024-09-11 18:39:50 UTC


README

此库专门用于验证数组类型输入数据,非常适合用于验证表单提交等任务。

我们受到了一个特定的库的启发,但由于具体要求,我们无法直接集成它。因此,这个包代表了一个定制版本,以满足我们的特定需求。

此包并未采用原始库的完整代码。这就是为什么该包不包含许多有用的验证规则和相应的代码。如果您需要,可以自由地复制和修改缺失的代码。

基本用法

namespace '...';

use Paysera\DataValidator\Validator\AbstractValidator;

class SomeValidator extends AbstractValidator
{
    public function __construct(RepositoryInterface $repository /* dependencies here */)
    {
        parent::__construct();

        $rule = new EntityExists($repository);
        $this->addRule($rule);
        $this->setRuleMessage($rule->getName(), 'error message for entity-exists rule');
        
        // for customisation of error for specific fields
        // you can use kind of MessageRepository here as a dependency
        $this->setAttributeMessage('field_name', 'custom_error_this_field');
    }
}

然后

$someValidator = new SomeValidator(/*dependencies here*/);

$rules = [
    'field1' => 'entity-exists|other_rules:with_parameters',
];

if (!$someValidator->validate($this->request->post /* or any other array with data */)) {
    $errors = $someValidator->getProcessedErrors();
}

/*
 * 'field' => [
 *     'entity-exists' => 'error message for entity-exists validator rule',
 *     'other_rules' => 'error message for other rules',
 * ]
 */

您可以使用占位符来显示消息

$this->setRuleMessage('entity-exists', 'Order status with ID=:id must exist');
// or
$this->setAttributeMessage('specific_field', 'Order status with ID=:id must exist');

在这种情况下,占位符将被正在检查的字段的值替换

添加新的验证规则

您必须创建一个新的类,其规则名称为驼峰式('entity-exists' => EntityExists)

您必须设置 $name 属性,如果需要一些特定的依赖项,则重写 __construct 方法,然后实现 validate 方法(因为它是一个抽象方法)。

请参阅 EntityExists 类和 AbstractValidatorTest 测试用例,作为规则及其使用的示例。

如前所述,您可以从原始库中获取代码并在此处使用,特别是验证规则代码。实际上,强烈建议这样做。

测试

bash run_tests.sh

或手动

docker build -t lib_plugin_data_validatior_tests -f $PWD/Dockerfile $PWD
docker run -it -v $PWD:/var/www -w /var/www lib_plugin_data_validatior_tests composer i
docker run -it -v $PWD:/var/www -w /var/www lib_plugin_data_validatior_tests composer run phpunit

测试调试

在构建了 lib_plugin_data_validatior_tests 容器之后,您可以使用它来在 IDE 中运行和调试测试。

在 Ubuntu 下设置 PHPStorm 的调试示例

创建解释器

Screenshot of error in Flare

Screenshot of error in Flare

Screenshot of error in Flare

配置解释器和文件映射

Screenshot of error in Flare

创建运行测试的端点

Screenshot of error in Flare

添加测试框架

Screenshot of error in Flare Screenshot of error in Flare

享受!