How can I describe the constraints for a nested collection of data using the Symfony validators XML notation for the rules?
I've tried to use the all
and collection
constraints and combine them somehow, but I can't get the offers validated. How can I validate the 2nd or even deeper data?
Test code:
<?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";
}
The validation.xml
file:
<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>
I believe the Valid
constraint should help you.
This constraint is used to enable validation on objects that are embedded as properties on an object being validated. This allows you to validate an object and all sub-objects associated with it.