phpro / api-problem-bundle

RFC7807 Problem details integration for Symfony
MIT License
22 stars 10 forks source link

Add symfony Validator Transformer #5

Closed leroy0211 closed 5 years ago

leroy0211 commented 5 years ago

Symfony Validator component has a built in feature to normalize a ConstraintViolationListInterface to an RFC7807 output. However, you need to do this by returning this yourself like so:

# IndexController.php

public function index(ValidatorInterface $validator) 
{
     $errors = $validator->validate(...);
     return $this->json($errors, 400);
}

It would be much nicer to throw an exception, because in the above example, it is very easy to mis the response status. And with an exception it doesn't.

Maybe something like:

throw new ApiValidationException($errors);

Or does this package already has a solution for it?

veewee commented 5 years ago

Hello @leroy0211,

This one is already built-in in the main package: https://github.com/phpro/api-problem#validationapiproblem

new ValidationApiProblem($errors);

You can wrap and throw an ExceptionApiProblem or create your own ValidationFailedException and add a transformer for that one.