kolurbo
kolurbo

Reputation: 538

How to properly validate JSON request in symfony 3.4

As the title says. How can I validate JSON request in symfony?

I found this package for validating JSON but it doesn't work with request object.

<?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
        }
    }
}

Whenever I send a POST request to that endpoint with correct value ({"new_layout": "blabla"}) it ends up in if clause - not valid.

What is a good approach to achieve that? Doesn't exist something like I could define how my incoming JSON would look like in comment section?

Upvotes: 3

Views: 6473

Answers (1)

kolurbo
kolurbo

Reputation: 538

The only solution what I've found so far is to convert JSON request to associated array manually and then verify:

    $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"
        ]
    ]);

The only thing that needs to be done: Every "type" => "object" must be renamed to "type" => "array"

Upvotes: 3

Related Questions