Api 平台 - DataTransformer 中的 DTO 验证

Api Platform - DTO validation in DataTransformer

我有一个 DTO 输入需要转换为实体对象。 DTO需要先验证,可能处于无效状态。

手册中有一节讨论了 DTO 的验证https://api-platform.com/docs/core/dto/#validating-data-transfer-objects,但它没有说明验证结果的用途,是应该传递到某个地方还是直接抛出。

final class MyDataDransformer implements DataTransformerInterface
{
    private ValidatorInterface $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    public function transform($dto, string $to, array $context = []): MyEntityObject
    {
        /** @var \Symfony\Component\Validator\ConstraintViolationList */
        $validationResult = $this->validator->validate($dto);

        if ($validationResult->count() > 0) {
            // how to throw exception with validation result here?
            // is this right place to throw this exception?
        }

        // if no validation errors, construct entity object and return as normal
    }

    public function supportsTransformation($data, string $to, array $context = []): bool
    {
        return true; // for simplicity
    }
}

Api 平台有处理实体对象验证异常的机制,它会格式化ConstraintViolationList对象并将所有错误输出为错误类型响应。我需要相同的 DTO。

api 平台中有一项服务会在出现违规时抛出异常。

它不是来自 symfony 的 ValidatorInterface,而是 api 平台一个

use ApiPlatform\Core\Validator\ValidatorInterface;