如何在 Symfony 约束组件中使用规范器选项

How to use normalizer option in Symfony constraints component

文档 https://symfony.com/doc/4.4/reference/constraints/Length.html#normalizer 表示

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.**

我能够像示例中那样调用 trim,甚至 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;
    }

    ...
}

但是由于某种原因,返回值没有改变值。我做错了什么,或者我如何将回调函数写入“normalizer”选项

Symfony 验证器不会更改您传递给它进行验证的值,它只是检查它们是否符合您指定的约束。 因此,在您的情况下,它将在检查长度以确保其有效时使用 trim,但会保留 DTO 属性供您处理。

我假设您一直在使用请求主体转换器侦听器将 fosrestbundle 标记转换为直接传递给 DTO 的数据?

当我需要类似的东西时,我所做的是使用 Symfony 序列化器通过它自己的非规范化器从请求数据生成我的 DTO,这传递了它期望的字段并通过执行以下操作准备了数据trim如果是字符串等,然后手动传递给验证器。