$rules = new Assert\Collection([
'userdata' => new Assert\Required([new Assert\Collection([
'fullname' => new Assert\NotBlank(),
'email' => new Assert\Email(),
'telephone' => new Assert\NotBlank(),
])
]),
"items" => new Assert\Required([
new Assert\Type('array'),
new Assert\NotBlank(),
new Assert\All([
new Assert\Type('array'),
new Assert\Collection([
"id" => new Assert\NotBlank(),
"quantity" => new Assert\NotBlank(),
])
])
]),
]);
$rules = new Assert\Collection([
"items" => new Assert\Required([
new Assert\NotBlank(),
new Assert\Callback(function ($value, ExecutionContextInterface $context) {
$validator = $context->getValidator();
$violations = $validator->validate($value, new Assert\Type('array'));
if ($violations->count() > 0) {
/** @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
$context
->buildViolation($violation->getMessage(), $violation->getParameters())
->atPath('items')
->addViolation()
;
}
return;
}
$violations = $validator->validate($value, new Assert\All([
new Assert\Type('array'),
new Assert\Collection([
"id" => new Assert\NotBlank(),
"quantity" => new Assert\NotBlank(),
])
]));
/** @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
$context
->buildViolation($violation->getMessage(), $violation->getParameters())
->atPath('items'. $violation->getPropertyPath())
->addViolation()
;
}
}),
]),
]);
$validator = Validation::createValidator();
$data = [
'items' => [
[
'id' => 'id',
'quantity' => 'quantity',
],
],
];
dump($validator->validate($data, $rules)); // Ok
$data = [
'items' => 1,
];
dump($validator->validate($data, $rules)); // Ko
$data = [
'items' => [
[
'id' => 'id',
'quantity' => 'quantity',
],
[
'id2' => 'id',
'quantity2' => 'quantity',
]
],
];
dump($validator->validate($data, $rules)); // Ko