Search code examples
phpsymfonyfosrestbundle

JMS Serializer intercept validation before controller action


I want to validate deserialized entity before controller action using param converter.

/**
 * @ParamConverter("post", converter="fos_rest.request_body")
 */
public function putPostAction(Post $post, ConstraintViolationListInterface $validationErrors)
{
    if (count($validationErrors) > 0) {
        // Handle validation errors
    }

    // ...
}

Instead of injecting contraintvalidation into controller, I want to return 400 and errors before controller action is executed.

How can I intercept FOSREST paramconverter?


Solution

  • The fos_rest.request_body converter just sets values from the request body if they exist in the entity. You can create your own ParamConverter class to handle creation of a Post from the request.

    In this class you can throw exceptions which would halt the flow before reaching the controller.

    Here's the Symfony documentation on ParamConverters:

    http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#creating-a-converter