Symfony Validator component: validating an object, reading the violations

Symfony's Validator component applies a class's constraints to an object and returns the list of violations, for a form as well as for plain code.

#[Route('/api/inscriptions', methods: ['POST'], format: 'json')]
public function __invoke(Request $request, ValidatorInterface $validator): JsonResponse
{
    $donnees = $request->toArray();
    $inscription = new Inscription((string) ($donnees['email'] ?? ''), (string) ($donnees['pseudo'] ?? ''));

    $violations = $validator->validate($inscription);
    if (\count($violations) > 0) {
        throw new ValidationFailedException($inscription, $violations); // 422 since Symfony 8.2
    }
    // …
}

validate() returns a ConstraintViolationList: empty, the object is valid; otherwise, each violation gives its getPropertyPath() and its getMessage(). It's the same service that $form->isValid() and #[MapRequestPayload] call: rules set on the entity apply everywhere, form, API or command. The trap: most constraints ignore empty values. #[Assert\Positive] accepts a null price, on purpose so constraints can be combined; without #[Assert\NotBlank] next to it, the empty price passes validation and it's the database that refuses to save it.

The exercises have you put on the Plat entity the constraints that reject a dish without a name, a negative price or a duplicate, without touching the controller or the form, then validate an API registration by hand and let the ValidationFailedException bubble up, which Symfony 8.2 turns into a 422 response listing the violations.

5 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

DoctrineSecurityAPI