简体   繁体   中英

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. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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