提问人:floriank 提问时间:11/2/2023 更新时间:11/3/2023 访问量:29
Symfony Validator:如何使用XML符号验证深度嵌套的数据?
Symfony Validator: How to validate deeply nested data using the XML notation?
问:
如何使用Symfony验证器XML表示法来描述嵌套数据集合的约束?
我尝试使用 and 约束并以某种方式将它们组合在一起,但我无法验证报价。如何验证第二个甚至更深的数据?all
collection
测试代码:
<?php
require 'vendor/autoload.php';
use Symfony\Component\Validator\Validation;
$validatorBuilder = Validation::createValidatorBuilder();
$validator = $validatorBuilder->enableAnnotationMapping()
->addXmlMapping('validation.xml')
->getValidator();
$transfer = new \Generated\Shared\Transfer\ProductConcreteTransfer();
$transfer->fromArray([
'numberOfOffers' => 0,
'defaultPrice' => null,
'offers' => [
[
'idProductOffer' => 1,
'merchantName' => null,
],
[
'idProductOffer' => 1,
'merchantName' => null,
]
]
]);
$result = $validator->validate($transfer);
if ($result->count() > 0) {
echo "Validation failed. Found " . $result->count() . " violation(s):\n";
foreach ($result as $violation) {
echo sprintf(
"Property: %s | Constraint: %s | Message: %s\n",
$violation->getPropertyPath(),
get_class($violation->getConstraint()),
$violation->getMessage()
);
}
} else {
echo "Validation passed. No violations found.\n";
}
文件:validation.xml
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="Generated\Shared\Transfer\ProductConcreteTransfer">
<property name="abstractSku">
<constraint name="Symfony\Component\Validator\Constraints\NotBlank"/>
</property>
<property name="defaultPrice">
<constraint name="Symfony\Component\Validator\Constraints\NotBlank"/>
</property>
<property name="numberOfOffers">
<constraint name="Symfony\Component\Validator\Constraints\NotBlank"/>
<constraint name="Symfony\Component\Validator\Constraints\Length">
<option name="min">1</option>
<option name="max">50</option>
</constraint>
</property>
<property name="offers">
<!-- How do I validate each entity in the collection? -->
</property>
</class>
</constraint-mapping>
答:
评论