加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

symfony2获取实体的所有验证约束(yml,xml,annotations)

发布时间:2020-12-16 22:58:01 所属栏目:百科 来源:网络整理
导读:我试图获得一个实体的所有验证约束并将这些约束转换为 Jquery验证规则,现在我能够获得注释定义的约束(感谢: Symfony2 get validation constraints on an entity),但是我在获取xml和yml时遇到了一些麻烦. $xml_file_loader = new XmlFileLoader("path_to_my_
我试图获得一个实体的所有验证约束并将这些约束转换为 Jquery验证规则,现在我能够获得注释定义的约束(感谢: Symfony2 get validation constraints on an entity),但是我在获取xml和yml时遇到了一些麻烦.

$xml_file_loader = new XmlFileLoader("path_to_my_project/vendor/friendsofsymfony/user-bundleFOSUserBundleResourcesconfigvalidation.xml");

使用类似的代码意味着我需要事先知道xml / yml文件的位置,我试图以某种方式编写一个可以自动执行此操作的通用代码.

有没有办法立刻获得所有约束?如果不是我怎么知道xml / yml文件的位置,并且在继承的情况下我需要检查父约束…这可行吗?

解决方法

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;
    }

返回:

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

可以配置或使用返回的数组来定义客户端验证规则,具体取决于您使用的客户端验证库/代码

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

对象$metadata现在包含有关您的特定实体的验证的所有元数据.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读