简体   繁体   English

独立类中的Symfony2 Validator约束

[英]Symfony2 Validator contraint in Standalone class

I am creating a class that accepts 3 parameters in its constructor and want to validate the property if it is of certain type. 我正在创建一个在其构造函数中接受3个参数的类,并希望验证该属性是否为某种类型。 Say I instantiate my class and give the object a parameter type of "string" with the corresponding property name and its value. 说我实例化我的类,并为对象提供参数类型“字符串”以及相应的属性名称及其值。 Below is the class I want to add validation on. 下面是我要添加验证的类。

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class SingleValueVariableBar implements VariableBarInterface
{
  protected $type;
  protected $property;
  protected $value;

  public function __construct($type, $property, $value)
  {
    $this->type      = $type;
    $this->property  = $property;
    $this->value     = $value;
   }

  /** 
   @Override Implements the VariableBarInterface interface
  */
  public function get($property)
  {
      if(!property_exists($this, $property)))
       throw new \Exception("The property $property does not exists.");
      return $this->{$property};
   }

  public static function loadValidatorMetadata(ClassMetadata $metadata)
  {
    $metadata->addPropertyConstraint('value', new Assert\Type(array(
      "??" => "??"
      )));
   }
 }

Say I create an instance of my class as shown below: 假设我创建了我的类的实例,如下所示:

<?php

   $svvb = new SingleValueVariableBar("string", "name", "Luyanda");

Now my class should validate whether the name property is in actual fact a string or not. 现在,我的班级应该验证name属性是否实际上是字符串。 if the first parameter is said to be an object and then I pass a string in the last parameter then validation should fail as the last parameter is a string. 如果第一个参数被认为是一个对象,然后我在最后一个参数中传递了一个字符串,则验证将失败,因为最后一个参数是一个字符串。

I need this to be as dynamic as possible. 我需要使它尽可能动态。 I have tried to check the internet on how the Type constraint can be used with regards to its parent class constructor ie Constraint. 我已经尝试检查Internet上如何使用关于其父类构造函数(即Constraint)的Type约束。

I finally have gotten it to work by making all properties static and then I initialize my validator object as follows: 我终于通过使所有属性静态化来使其工作,然后按如下所示初始化验证器对象:

<?php

 $metadata->addPropertyConstraint('value', new AssertType(self::$type));

This works perfectly and I can have parameters validated against each other as per my requirement. 这非常有效,我可以根据自己的要求对参数进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM