我有一个需要转换为实体对象的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。
发布于 2020-10-23 07:18:31
api平台中有一个服务,如果存在违规,它会抛出异常。
它不是symfony的ValidatorInterface,而是api platform。
use ApiPlatform\Core\Validator\ValidatorInterface;
https://stackoverflow.com/questions/64490166
复制相似问题