我需要创建一个Symfony 2 自定义类约束验证器,以验证一个属性不等于另一个(即密码不能匹配用户名)。
我的第一个问题是:我需要实现方法getDefaultOption()
和用途吗?
/**
* @Annotation
*/
class NotEqualTo extends Constraint
{
/**
* @var string
*/
public $message = "{{ property1 }} should not be equal to {{ property2 }}.";
/**
* @var string
*/
public $property1;
/**
* @var string
*/
public $property2;
/**
* {@inheritDoc}
*/
public function getRequiredOptions() { return ['property1', 'property2']; }
/**
* {@inheritDoc}
*/
public function getTargets() { return self::CLASS_CONSTRAINT; }
}
第二个问题是,如何在我的validate()
方法中获取实际对象(检查“property1”和“property2”)?
public function validate($value, Constraint $constraint)
{
if(null === $value || '' === $value) {
return;
}
if (!is_string($constraint->property1)) {
throw new UnexpectedTypeException($constraint->property1, 'string');
}
if (!is_string($constraint->property2)) {
throw new UnexpectedTypeException($constraint->property2, 'string');
}
// Get the actual value of property1 and property2 in the object
// Check for equality
if($object->property1 === $object->property2) {
$this->context->addViolation($constraint->message, [
'{{ property1 }}' => $constraint->property1,
'{{ property2 }}' => $constraint->property2,
]);
}
}