我有一个DTO输入,需要将其转换为Entity对象。 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。
答案 0 :(得分:2)
api平台中有一项服务,如果存在违规,则会引发异常。
这不是symfony的ValidatorInterface,而是api平台的一个
use ApiPlatform\Core\Validator\ValidatorInterface;