Search code examples
phpsymfonysymfony-validator

Use Symfony validator in Method arguments


Is there any way to apply Symfony Validator constraints to method's arguments?

Something like this:

use Symfony\Component\Validator\Constraints as Assert;

class acmeClass
{
  /**
  * @param $argument
  * @Assert\Choice({"YES", "NO"})
  */
  public funciton foo($argument) 
  {
    /..  
  }
}

So if $argument has different value than the given choices, validation throws an exception?


Solution

  • Unfortunately this is not supported by Symfony framework.

    You have 2 choices:

    1). Validate before calling foo():

    $errors = $validator->validate($argument, $constraint);
    if (count($errors) > 0) {
        //throw some exception?
    }
    
    $acmeClassObj->foo($argument);
    

    2). Validate inside foo() itself:

    class acmeClass
    {
        public function foo($argument)
        {
            $errors = $validator->validate($argument, $constraint);
            if (count($errors) > 0) {
                //throw some exception?
            }
    
            //do something here with $argument
        }
    }
    

    Honestly I think it's better that Symfony doesn't support this. Annotations and comments in general are often overlooked by programmers when reading code and they can often be left out-of-date, resulting in harder to debug code.