phpsymfonyfosrestbundlesymfony-validator

How to use normalizer option in Symfony constraints component


The documentation https://symfony.com/doc/4.4/reference/constraints/Length.html#normalizer states that

This option allows to define the PHP callable applied to the given value before checking if it is valid.

For example, you may want to pass the 'trim' string to apply the trim PHP function in order to ignore leading and trailing whitespace during validation.**

I was able to call trim as in the example, and even the static function of the class:

class PersonDto
{
    /**
     * @Assert\Length(min="1", max="255", allowEmptyString=false, normalizer="App\Dto\PersonDto::foo")
     */
    private ?string $name = null;

    public static function foo($value) {
        $value = 'the text has been replaced';
        return $value;
    }

    ...
}

But for some reason the returned value does not change the value. What am I doing wrong, or how do I write a callback function into "normalizer" option


Solution

  • The Symfony validator does not change the values you pass it to validate, it merely checks that they adhere to the constraints you have assigned. So in your case it will use the trim when checking the length to make sure it is valid but will leave the DTO properties as is for you to deal with.

    I assume with the fosrestbundle tag you have been using the Request Body Converter Listener to convert the data passed directly to a DTO?

    What I did when in need of something similar was to use the Symfony Serializer to generate my DTO from the request data with its own denormalizer, this made a pass over the fields it is expecting and prepared the data by doing a trim if it was a string etc. and then passed it to the validator manually.