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.

Installing PECL YAML on Mac OSX Lion

If you are trying to install YAML via PECL on Lion, you may get an error such as the following.

configure: error: Please install libyaml
ERROR: `/private/tmp/pear/install/yaml/configure --with-yaml' failed

Some solutions on the internet suggest installing it via a package manager.

rvm pkg install libyaml

However, although this process will claim to work, when you come to run the command again, it will fail at the same point. Instead, you need to download libyaml, which you can do here, then extract it, cd into the directory and run the following commands.

./configure
make
make install

You don’t need to sudo. You should now be able to run the install command again.

sudo pecl install --ignore-errors yaml

This time it should be successful.

Conflict error on PECL YAML

If you are trying to install PECL YAML on Mac OS X Lion, you may find you get a conflict with an error message similar to the following.

WARNING: pecl.php.net/yaml: conflicting files found:
yaml/LICENSE (pear.symfony-project.com/yaml)

This error is documented on GitHub and as it is not critical, can be overcome by turning off errors.

pecl install --ignore-errors yaml

On running that command, it should no longer stop at that point.

Missing psych (for YAML output)

If you’re using YAML in Ruby and have it installed via RVM, you might get a notice similar to the following.

It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.

You can solve this using the following commands.

rvm pkg install libyaml
rvm reinstall 1.9.3

You may (or even need) to replace 1.9.3 with your exact version number.