Set the parameter as needed without specifying it on the route in Symfony2

I have an action defined as

/**
 * @Route("/doSomething/{someId}", name="do_something")
 * @Method("GET")
 * @ParamConverter("someId", class="MyBundle:Something")
 */
public function someAction(Something $something) {
    ...
}

I would like to use the token parameter passed as the β€œnormal” query string parameter, for example:

/myController/doSomething/5?token=2a47c2ff18a5d53cbaa5840b6c7c4008

What would be a suitable way to make this parameter necessary and establish some requirements for it, for example, to comply ^[\da-z]+$? Is there a way to indicate this in annotation syntax?

As I see it, this will do it manually, for example:

public function someAction(Something $something, Request $request) {
    $token = $request->query->get('token');
    $regexConstrain = new Regex('^[\da-z]+$');
    $regexConstrain->message = 'Invalid token';

    $errors = $this->get('validator')->validate($token, $regexConstrain);

    if (count($errors)) {
        throw new \InvalidArgumentException($errors[0]->getMessage());
    }

    ...
}

But is there a faster, built-in way to do this?

+4
source share
1 answer

, , , OptionsResolver , .

, OptionResolver .

use Symfony\Component\OptionsResolver\OptionsResolver;

public function someAction(Something $something, Request $request)
{
    $resolver = new OptionsResolver();
    $resolver->setAllowedValues('token', function ($value) {
        return (bool) preg_match('/^[\da-z]+$/', $value);
    });

    // will throw a `Symfony\Component\OptionsResolver\Exception\InvalidArgumentException`
    // if token doesn't match the regex
    $resolver->resolve($request->query->all());

    ...
}
+2

All Articles