我尝试验证的类有一个属性,它可以是空数组或某些对象的数组:
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
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 = [],