2012-09-20 123 views
1

我需要創建Symfony 2 custom class constraint validator,以驗證屬性不等於另一個屬性(即密碼不能與用戶名匹配)。自定義Symfony 2類約束驗證程序NotEqualTo

我的第一個問題是:我需要實施方法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; } 
} 

第二個問題是,如何獲取實際的對象(檢查 「property1」 和 「property2」)在我的validate()方法?

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, 
     ]); 
    } 
} 

回答

3

,我需要實現方法getDefaultOption(),什麼是被用來做什麼?

您不必這樣做,但是如果您的註釋具有單個「領先」屬性,強烈建議這麼做。註釋的屬性定義鍵 - 值對的列表,如:

@MyAnnotation(paramA = "valA", paramB = "valB", paramC = 123) 
@MaxValue(value = 199.99) 

使用getDefaultOption()你可以告訴註解處理器哪個選項是默認。如果您想定義paramA作爲@MyAnnotationvalue默認選項爲@MaxValue默認選項你可以寫:

@MyAnnotation("valA", paramB = "valB", paramC = 123) 
@MaxValue(199.99) 
@MaxValue(199.99, message = "The value has to be lower than 199.99") 

如何獲取實際的對象(檢查「property1 「和」property2「)在我的validate()方法?

您必須創建一個級別的約束註釋。然後在你的validate()方法中的$value參數將是一個完整的對象而不是單個屬性。

+0

關於第一個問題,我的選項是「property1」和「property2」,所以沒有「領先」選項。我對嗎? – gremo

+0

@格雷莫:是的,你說得對。 – Crozin

+0

謝謝,非常有幫助的解釋。 – gremo