<?php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\ValidatorBuilder;
/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*/
class Bacon extends Constraint
{
public $message = 'The validator checks bacon and your argument is invalid.';
}
class BaconValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Bacon) {
throw new UnexpectedTypeException($constraint, Bacon::CLASS);
}
if ('bacon' === strtolower($value)) {
return;
}
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value),
));
}
}
// see http://php.budgegeria.de/inyvqngvba6 for how symfony validation with annotation works
class Foo
{
/**
* @Bacon
*/
public $breakfast;
}
$foo = new Foo();
$foo->breakfast = 'not bacon';
$validator = (new ValidatorBuilder())
->enableAnnotationMapping()
->getValidator();
$violationList = $validator->validate($foo);
foreach($violationList as $v) {
echo $v->getMessage() . PHP_EOL;
}