D
D
Daria Motorina2020-09-20 18:37:34
symfony
Daria Motorina, 2020-09-20 18:37:34

How to properly validate raw query parameters in Symfony?

I am using Symfony 5.0.

I understand that I am going very wrong in an attempt to set validation for an optional GET parameter.
You need to validate that the param parameter can only have a true|false value.
Right now I have mutually exclusive paragraphs in my code - getting a GET parameter and casting it to bool nullifies the validation, and the raw GET parameter is of type string, not bool and so the validation doesn't work as intended.

Surely there is a cleaner way, but the search does not yield results. Prompt approach or the link to an example, please.

Request: GET /neo/fastest?hazardous=true
Code:

/**
     * @Route("/neo/fastest", name="neo_fastest", methods={"GET"})
     */
    public function getFastestNearEarthObject(Request $request)
    {
        $constraints = new Collection([
            'hazardous' => [new Optional(new Type(['type' => 'boolean']))],
        ]);

        $errors = $this->validate($request->get('hazardous', false), $constraints);

        if ($errors) {
            return $this->json($errors, 400);
        }

        $isHazardous = filter_var($request->get('hazardous', false), FILTER_VALIDATE_BOOLEAN);
        //other code
   }

    /**
     * @param $value
     * @param $constraints
     *
     * @return array|void
     */
    protected function validate($value, $constraints)
    {
        $validator = Validation::createValidator();
        $violations = $validator->validate($value, $constraints);
        $messages = [];

        if (0 === count($violations)) {
            return;
        }

        foreach ($violations as $violation) {
            /* @var ConstraintViolation $violation */
            $messages[] = $violation->getMessage();
        }

        return $messages;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Zhdanovskikh, 2020-09-24
@andrew72ru

$isHazardous = $request->query->getBoolean('hazardous');

Will be trueif passed "true" or 1, and falseif "false" or 0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question