gpt4 book ai didi

symfony2 获取实体上的所有验证约束(yml、xml、注释)

转载 作者:行者123 更新时间:2023-12-05 01:09:39 24 4
gpt4 key购买 nike

我试图获取实体上的所有验证约束并将这些约束转换为 Jquery 验证规则,现在我能够获得注释定义的约束(感谢:Symfony2 get validation constraints on an entity),但是我在获取 xml 和 yml 约束时遇到了一些麻烦。

$xml_file_loader = new XmlFileLoader("path_to_my_project/vendor/friendsofsymfony/user-bundle\FOS\UserBundle\Resources\config\validation.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现在包含有关与您的特定实体有关的验证的所有元数据。

关于symfony2 获取实体上的所有验证约束(yml、xml、注释),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15573935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com