symfony2 get all validation constraints on an entity (yml, xml, annotations)

不问归期 提交于 2019-11-30 21:51:06
Robin Rizvi
private function getValidations()
    {
        $validations=[];
        $validator=$this->get("validator");
        $metadata=$validator->getMetadataFor(new your_entity());
        $constrainedProperties=$metadata->getConstrainedProperties();
        foreach($constrainedProperties as $constrainedProperty)
        {
            $propertyMetadata=$metadata->getPropertyMetadata($constrainedProperty);
            $constraints=$propertyMetadata[0]->constraints;
            $outputConstraintsCollection=[];
            foreach($constraints as $constraint)
            {
                $class = new \ReflectionObject($constraint);
                $constraintName=$class->getShortName();
                $constraintParameter=null;
                switch ($constraintName) 
                {
                    case "NotBlank":
                        $param="notBlank";
                        break;
                    case "Type":
                        $param=$constraint->type;
                        break;
                    case "Length":
                        $param=$constraint->max;
                        break;
                }
                $outputConstraintsCollection[$constraintName]=$param;
            }
            $validations[$constrainedProperty]=$outputConstraintsCollection;
        }
        return $validations;
    }

Returns:

array(13) (
      [property1] => array(4) (
        [NotBlank] => (string) notBlank
        [NotNull] => (string) notBlank
        [Type] => (string) string
        [Length] => (int) 11
      )
      [property2] => array(4) (
        [NotBlank] => (string) notBlank
        [NotNull] => (string) notBlank
        [Type] => (string) string
        [Length] => (int) 40
      )
      ..........
)

The returned array can be configured or used to define client side validation rules depending on the client-side validation library/code that you are using

$validator=$this->get("validator");
$metadata=$validator->getMetadataFor(new yourentity());

The object $metadata now contains all the metadata about validations that concerns your specific entity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!