如何验证数组是否可以为空

问题描述 投票:0回答:1

我尝试验证的类有一个属性,它可以是空数组或某些对象的数组:


use App\Api\Dto\WorkHour as WorkHourDto;
use Symfony\Component\Serializer\Annotation\Groups as SerializerGroups;
use Symfony\Component\Validator\Constraints as Assert;

[....]

        #[Assert\All(
            new Assert\Type(type: WorkHourDto::class)
        )]
        #[Assert\Valid(groups: ['create', 'update'])]
        #[SerializerGroups(['view', 'create', 'update'])]
        public array $workHours = []
[....]

断言这一点的正确方法是什么?目前,如果数组为空,验证就会失败。

我看过 then When Constraint [https://symfony.com/doc/6.4/reference/constraints/When.html],但似乎它只是用于检查复杂的细节。

当然,我可以完全省略验证,或者只断言它是一个数组,但这将是我最后的手段。

我在 php8.2 上运行 symfony 6.4

validation symfony6 php-8.2
1个回答
0
投票

将其包裹成

Assert\AtLeastOneOf

    #[
        Assert\AtLeastOneOf([
            new Assert\Count(max: 0),
            new Assert\All(
                new Assert\Type(type: WorkHourDto::class)
            ),
        ]),
        Assert\Valid(groups: ['create', 'update']),
        SerializerGroups(['view', 'create', 'update']),
    ]
    public array $workHours = [],
© www.soinside.com 2019 - 2024. All rights reserved.