PUT/PATCH 带有不允许字段的请求

PUT/PATCH request with not allowed fields

我有一个用 Symfony 4 框架编写的应用程序。我有一个 PUT/PATCH 请求,其中可能包含错误的请求字段。例如,实体用户不应包含字段 description。在这种情况下,我想阻止请求和 return 错误的请求响应。我想知道在 Symfony 4 中最好的方法是什么?

In node.js implenentation such problem looks like below: 

router.patch('/tasks/:id', async (req, res) => {
    const updates = Object.keys(req.body)
    // allowed fields
    const allowedUpdates = ['description', 'completed']
    // check if there are bad fields
    const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
    if (!isValidOperation) {
        return res.status(400).send({ error: 'Invalid updates!' })
    }
    /*
    some response code
    /*
})

如何在 Symfony 4 框架中做类似的事情?

first, by default when option allow_extra_fields is set to false (default), form with extra fields would not validate, more about this setting: https://symfony.com/doc/current/reference/forms/types/form.html#allow-extra-fields

接下来你可以检查$form->getExtraData()是否是一个空数组,这意味着没有额外的字段

如果发现额外的字段导致错误的请求响应,您可以:

throw new BadRequestHttpException();

或无一例外:

return $this->json(['error' => 'your error'], Response::HTTP_BAD_REQUEST);

return new JsonResponse(['error' => 'your error', Response::HTTP_BAD_REQUEST]);