使用Symfony Validator不扩展Compound约束的复合验证规则

uinbv5nw  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(203)

我使用验证器组件作为数据验证的独立包。
我有一个类,它包含返回常见验证案例的方法,比如这个:

public function selectOneFrom(array $choices): Constraint
    {
        return new RequireAll([
            new Symfony\Component\Validator\Constraint\NotNull(),
            new Symfony\Component\Validator\Constraint\Choice($choices),
        ]);
    }

据我所知,返回复合规则的唯一选择是将其作为array返回。我所追求的是在这些返回复合规则的方法上没有: Constraint|array返回值类型提示。
我不明白的是为什么没有具体的Compound约束。在这里,我创建了自己的RequireAll,它扩展了Compound,非常简单:

class RequireAll extends Compound
{
    public function __construct(iterable $constraints, $options = null)
    {
        parent::__construct($options);
        $this->constraints = is_array($constraints) ? $constraints : iterator_to_array($constraints);
    }

    protected function getConstraints(array $options): array
    {
        return $this->constraints;
    }
}

我错过什么了吗?
P.S.:我知道我应该扩展Compound类,但这样我可以参数化规则,而不是为每个复合验证规则创建一个新类。

oyxsuwqo

oyxsuwqo1#

我知道我应该扩展Compound类,但是通过这种方式,我可以对规则进行参数化,而不是为每个复合验证规则创建一个新类。
但是,真的会更少努力吗?

class SelectOneFrom extends Compound
{
    public array $choices;

    protected function getConstraints(array $options): array
    {
        return [
            new Symfony\Component\Validator\Constraint\NotNull(),
            new Symfony\Component\Validator\Constraint\Choice($options['choices']),
        ];
    }

    public function getRequiredOptions()
    {
        return ['choices'];
    }

    public function getDefaultOption()
    {
        return 'choices';
    }
}

这是更多的代码,如果你是计数行,但它仍然相当简单。在Compound约束之前,创建等效的SelectOneFrom约束要困难得多。
拥有SelectOneFrom约束的好处是,它比依赖于对::selectOneFrom工厂方法的调用要容易得多。* (即,如果您使用XML或Attributes来设置对象属性的约束。)*
另一种方法是既不定义SelectOneFrom也不定义RequireAll约束,只让工厂方法返回一个数组。

/**
     * @return Constraint[]
     */
    public function selectOneFrom(array $choices): array
    {
        [
            new Symfony\Component\Validator\Constraint\NotNull(),
            new Symfony\Component\Validator\Constraint\Choice($choices),
        ];
    }

如果您的项目可以调用一个工厂方法,那么让它返回一个约束数组就等于返回一个RequireAll约束。

相关问题