Class constraints in Symfony2

Sometimes you need to put a constraint on a whole class, rather than a single value. Duplicate usernames are a good example of this – you don’t want to be able to set a username to one that is already in use – but if it is in use with the user you are currently working on, you don’t want to flag it up as an error!

Lets use that as an example. You have a Username constraint and a UsernameValidator object to do the actual validation. We need to supply the validator an object, so we need to put the following method inside the Username object.

public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

This will turn the first parameter in our isValid function in the UsernameValidator class to an object.

public function isValid($user, Constraint $constraint)

Finally, you can call the constraint from your YAML validation file.

User:
    constraints:
        - nocs:UniqueUsername: ~

Normally, under user you would have getters and properties – but here we’re adding a new section named “constraints” which lists all the class constraints.

Validation in Symfony2 unit tests

Want to use the Validation module in your Symfony2 unit tests? No problem, thanks to the ValidatorFactory, it’s relatively straight forward.

use Symfony\Component\Validator\ValidatorFactory;

class ExampleTest extends \PHPUnit_Framework_TestCase
{
    public function testSomething()
    {
        $validator = ValidatorFactory::buildDefault()->getValidator();
    }
}

Simply include the ValidatorFactory namespace and then use the class and it’s default values method to deliver you a validator, which you can then validate your objects against just as if it was in a controller.