如何在Symfony 3.4中正确验证JSON请求

时间:2018-08-13 10:10:57

标签: php symfony

如标题所述。如何在symfony中验证JSON请求?

我发现这个package用于验证JSON,但不适用于请求对象。

<?php

namespace AppBundle\Controller;

use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use JsonSchema\Validator;


class ApiController extends Controller
{


    /**
     * @Route("/api/store-data", name="store-data", methods={"POST"})
     * @param Request $request
     * @param LoggerInterface $logger
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function storeDashboardLayout(Request $request, LoggerInterface $logger)
    {
        $validator = new Validator();
        $validation = $validator->validate(
            $request,
            (object)[
                "type" => "object",
                "properties" => (object)[
                    "new_layout" => (object)[
                        "type"=> "string"
                    ]
                ],
                "required" => [
                    "new_layout"
            ]
        ]);

        if(!$validator->isValid()){
            // json is not valid do something
        }
    }
}

每当我以正确的值({"new_layout": "blabla"})向该端点发送POST请求时,该请求都会以if子句结尾-无效。

有什么好的方法可以实现?是否不存在可以在注释部分定义传入的JSON的外观?

1 个答案:

答案 0 :(得分:3)

到目前为止,我发现的唯一解决方案是手动将JSON请求转换为关联的数组,然后进行验证:

    $data = json_decode($request->getContent(), true);
    $validator = new Validator();
    $validation = $validator->validate(
        $data,
        (object)[
            "type" => "array",
            "properties" => (object)[
                "new_layout" => (object)[
                    "type"=> "string"
                ]
            ],
            "required" => [
                "new_layout"
        ]
    ]);

唯一需要做的事情: 每个"type" => "object"必须重命名为"type" => "array"