【发布时间】: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。
【问题讨论】: