如何在restful api中验证来自帖子的数据

问题描述 投票:1回答:1

我需要在插入数据库之前验证一些数据,因为我创建了一个从实体返回无效字段的小服务。验证单个实体时,它可以正常工作。

class EntityValidator
{
    protected $validator;

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

    public function validate($entity)
    {
        $errors = $this->validator->validate($entity);
        $response = null;
        if ($errors->count()) {
            foreach ($errors as $error) {
                $response[$error->getPropertyPath()] = $error->getMessage();
            }
        }

        return $response;
    }
}

但是我一直在努力验证更复杂的问题,例如:这是一个宁静的api端点,它接收带有user_id的json和帖子正文中的百分比,它将验证实体是否正确映射为symfony验证器约束。

public function create(Request $request, EntityValidator $entityValidator)
{
    $data = json_decode($request->getContent(), true);
    $entityExample = new EntityExample();
    $entityExample
         ->setUserId($data['user_id'])
         ->setPercentage($data['percentage'])
    ;
    $errors = $entityValidator->validate($entityExample);
    // .. do other things ..
    return new JsonResponse($errors);    
}

但是让我说我​​收到一组数据,我将一次插入多行,并且有一个业务逻辑,说“用户的百分比总和需要为100”

public function create(Request $request, EntityValidator $entityValidator)
{
    $data = json_decode($request->getContent(), true);
    $totalPercentage = 0;
    foreach ($data as $element) {
         $entityExample = new EntityExample();
         $entityExample
             ->setUserId($element['user_id'])
             ->setPercentage($element['percentage'])
         ;
         $totalPercentage += $element['percentage'];
    }
    $errors = $entityValidator->validate($entityExample);
    if ($totalPecentage != 100) {
        $errors[] = 'Sum of percentage must be 100';
    }
    // .. do other things ..
    return new JsonResponse($errors);    
}

似乎错误的是将这种业务逻辑保留在控制器中,但我不知道在哪里放置它,我应该为此创建一个服务吗?那么每个具有更复杂验证的端点都将创建一个新服务?

php symfony model-view-controller code-structure symfony-validator
1个回答
3
投票
  1. 创建JSON请求有效负载的模型表示。具有公共属性的模型,没有别的。例如让我们说模型被称为Sale
  2. 创建一个自定义Validation Constraint,它将与Sale模型连接。在此验证类中,您将遍历Sale.percentage属性并运行验证逻辑。
  3. 在控制器中,调用序列化程序组件和验证程序组件来验证请求。

以上各点的完整示例:

  1. 下面的两个链接都有模型示例,但如果您想要更多示例,请在此页面中执行ctrl + f json http://www.inanzzz.com/index.php/posts/symfony
  2. Class level custom assert validation constraint in symfony
  3. A simple way of handling request, response and exceptions in Symfony API。复制,不要触摸AbstractController。做UserController::create为您自己的控制器做什么。他在同一个控制器中使用$this->data进行演示,但是你应该将它传递给服务并在那里进行处理。
© www.soinside.com 2019 - 2024. All rights reserved.