Symfony Validator:如何使用XML符号验证深度嵌套的数据?

idv4meu8  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(153)

如何使用Symfony验证器XML表示规则来描述嵌套数据集合的约束?
我尝试使用allcollection约束,并以某种方式将它们合并组合起来,但我无法验证报价。我如何验证第二个或更深层次的数据?
测试代码:

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

y4ekin9u

y4ekin9u1#

我相信Valid约束应该对您有所帮助。
此约束用于对作为属性嵌入到要验证的对象上的对象启用验证。这允许您验证对象以及与之关联的所有子对象。

相关问题