validationsymfony6php-8.2

How to validate an array which can be empty


My class, which I try to validate, has a property, which can be either an empty array or an array of certain objects:


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 = []
[....]

What would be the correct way to assert this? Currently the validation fails if the array is empty.

I have seen then When Constraint [https://symfony.com/doc/6.4/reference/constraints/When.html], but it seems that it is only for checking complex details.

Of course I can leave out the validation at all or only assert that it is an array, but that would be my last resort.

I am running symfony 6.4 on php8.2


Solution

  • Wrap it into 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 = [],
    

    PHP-only approach would be to have setter:

        private array $workHours = [];
    
        public function setWorkHours(WorkHourDto ...$workHours) {
            $this->workHours = $workHours;
        }