【问题标题】:Api Platform - DTO validation in DataTransformerApi 平台 - DataTransformer 中的 DTO 验证
【发布时间】:2020-10-22 20:36:03
【问题描述】:

我有一个需要转换为实体对象的 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 Platform 具有处理实体对象验证异常的机制,它将格式化 ConstraintViolationList 对象并将所有错误输出为错误类型响应。我需要同样的 DTO。

【问题讨论】:

    标签: symfony api-platform.com


    【解决方案1】:

    api平台有一个服务,如果有违规就会抛出异常。

    不是 symfony 的 ValidatorInterface,而是 api 平台的

    use ApiPlatform\Core\Validator\ValidatorInterface;

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2022-10-22
      • 1970-01-01
      • 2019-12-23
      • 2013-03-05
      • 1970-01-01
      • 2012-04-10
      • 2022-08-05
      • 1970-01-01
      相关资源
      最近更新 更多