Php 如何从FOSRestBundle为RESTful API中的POST方法设置适当的JSON响应?

Php 如何从FOSRestBundle为RESTful API中的POST方法设置适当的JSON响应?,php,json,symfony,fosrestbundle,symfony-2.6,Php,Json,Symfony,Fosrestbundle,Symfony 2.6,我正在为RESTful API制作一个POST方法。正如您可能注意到的那样,该API构建在FOSRestBundle和NelmioApiDoc之上。我无法验证文件是否未上载或rid参数是否丢失以及是否使用正确的JSON进行响应。这就是我正在做的: /** * Set and upload avatar for reps. * * @param ParamFetcher $paramFetcher * @param Request $request * * @ApiDoc( *

我正在为RESTful API制作一个
POST
方法。正如您可能注意到的那样,该API构建在FOSRestBundle和NelmioApiDoc之上。我无法验证文件是否未上载或
rid
参数是否丢失以及是否使用正确的JSON进行响应。这就是我正在做的:

/**
 * Set and upload avatar for reps.
 *
 * @param ParamFetcher $paramFetcher
 * @param Request $request
 *
 * @ApiDoc(
 *      resource = true,
 *      https = true,
 *      description = "Set and upload avatar for reps.",
 *      statusCodes = {
 *          200 = "Returned when successful",
 *          400 = "Returned when errors"
 *      }
 * )
 *
 * @RequestParam(name="rid", nullable=false, requirements="\d+", description="The ID of the representative")
 * @RequestParam(name="avatar", nullable=false, description="The avatar file")
 *
 * @return View
 */
public function postRepsAvatarAction(ParamFetcher $paramFetcher, Request $request)
{
    $view = View::create();
    $uploadedFile = $request->files;

    // this is not working I never get that error if I not upload any file
    if (empty($uploadedFile)) {
        $view->setData(array('error' => 'invalid or missing parameter'))->setStatusCode(400);
        return $view;
    }

    $em = $this->getDoctrine()->getManager();
    $entReps = $em->getRepository('PDOneBundle:Representative')->find($paramFetcher->get('rid'));

    if (!$entReps) {
        $view->setData(array('error' => 'object not found'))->setStatusCode(400);
        return $view;
    }

    .... some code

    $repsData = [];

    $view->setData($repsData)->setStatusCode(200);

    return $view;
}
如果我没有上传文件,我会得到以下响应:

Error: Call to a member function move() on a non-object
500 Internal Server Error - FatalErrorException
但是由于Symfony异常错误不是我想要和需要的JSON,所以代码永远不会进入
if

如果我没有设置
rid
,那么我得到了这个错误:

Request parameter "rid" is empty
400 Bad Request - BadRequestHttpException

但同样是Symfony异常错误,而不是JSON。如果
rid
不存在或文件未上载,如何响应正确的JSON?有什么建议吗?

$request->files
文件包的一个实例。使用
$request->files->get('keyoffileinrequest')
获取文件

rid
是一个必需的参数,所以如果您不设置它,它会抛出一个BadRequestHttpException。它的行为应该是这样的。您应该尝试将
rid
设置为数据库中不存在的ID,然后您应该会看到自己的错误消息

如果希望
rid
是可选的,可以为
rid
添加默认值:

* @RequestParam(name="rid", nullable=false, requirements="\d+", default=0, description="The ID of the representative")

差不多吧。现在
rid
将为零,您的Repository::find调用可能会返回null,并且您的错误视图将返回。但我建议您保持原样,这是正确的行为。

您缺少
$uploadedFile
参数或设置变量。@LordZed我已经编辑了我的答案,我已经定义了
$uploadedFile