dbt/staged-validation

Laravel的阶段性验证

3.0.0 2022-05-09 16:55 UTC

This package is auto-updated.

Last update: 2024-09-09 22:00:51 UTC


README

此软件包提供了一种在各个阶段轻松验证请求数据的方法。这在您希望在执行对数据库或外部服务的复杂操作之前先验证标量数据的情况下非常有用。

此外,该软件包还提供了一种方便的方式在您的Rule类中缓存数据,这样您就无需两次查找记录(例如,一次在表单请求中,一次在控制器中)。

安装

composer require dbt/staged-validation

用法

捆绑

通过扩展抽象的StageBundle定义一组阶段。它可能看起来像这样

use Dbt\StagedValidation\StageBundle;

class MyBundle extends StageBundle
{
    /**
     * @return \Dbt\StagedValidation\StageInterface[]
     */
    public function stages (): array
    {
        return [
            new FirstStage(),
            new SecondStage(),
        ];
    }
}

阶段

每个阶段都应该扩展抽象的Stage类。例如

use Dbt\StagedValidation\Stage;

class FirstStage extends Stage
{
    public function name (): string
    {
        return 'first_stage';
    }

    public function rules (): array
    {
        return [
            'my_string' => [
                'required',
                'string',
                'min:10',
            ],
        ];
    }
}

验证

只需在控制器中为捆绑添加类型提示即可

class MyController {
    public function __invoke (MyBundle $bundle) {
        // Get all the validated data from each stage.
        $all = $bundle->all();

        // Get the validated data from a specific stage.
        $first = $bundle->get('first_stage');
    }
}

每个阶段将单独验证。这意味着如果某个阶段验证失败,则下一个阶段将不会运行。

保留实体

如果您希望保留检索到的实体,请扩展CachedRule类。它只是一个具有略微不同界面的Laravel Rule

use Dbt\StagedValidation\CachedRule;

class RuleStub extends CachedRule
{
    public function message ()
    {
        return 'my failure message';
    }

    public function fetch ()
    {
        // Fetch from an external resource. Under the hood, whatever you
        // return here will be assigned to $this->cached.
    }

    protected function passesAfterFetch ($attribute, $value)
    {
        // Perform validation as you normally would, keeping in mind that
        // $this->cached has already been assigned.
        return $this->cached->someMethod() === $value;
    }
}

保留的实体将作为部分捆绑有效载荷与原始值一起序列化。因此,如果名为second_stage的阶段为名为my_attribute的属性有一个缓存的规则,您将看到一个具有此形状的集合

// $bundle->get('second_stage')->toArray()
[
    'second_stage' => [
        'my_attribute' => // the original data,
        'my_attribute_cached' => // the fetched entity
    ],
];

扩展

如果您希望编写自己的实现,可以实现对提供的任何接口:CachedRuleInterfaceStageBundleInterfaceStageInterface

如果您希望更改给定阶段的验证器实现,可以覆盖Stage::validatorResolver()方法。

等等。

有关详细信息,请参阅贡献指南。MIT许可证(MIT)。有关更多信息,请参阅许可证文件