php - symfony assertions raw data validation with if/else statement
Get the solution ↓↓↓
I have a such json:
{
"id":1,
"name":"some name",
"decorations":[
{
"id":1,
"options":[
{
"type":"color",
"label":"Color",
"items":[
{
"label":"Green shades",
"color_group":{
"shade":"green",
"name":"Green"
},
"colors":[
{
"rgb":"249,249,249",
"hex":"#FBFBFB"
},
{
"rgb":"249,249,250",
"hex":"#FBFBFF"
}
]
},
{
"label":"White shades",
"color_group":{
"shade":"white",
"name":"White"
},
"colors":[
{
"rgb":"255,255,255",
"hex":"#FFFFFF"
}
]
}
]
},
{
"type":"position",
"label":"Position",
"items":[
{
"label":"Front"
},
{
"label":"Back"
}
]
}
]
}
]
}
which I want to validate, rules are:
id,name,decoratorsrequired- each decorator should have
idandoptions- each option should have
type,labelanditems. each option has few types, all of them has same structure of each item except of acolortype- so each item should have
label, and in case ofcoloroption each item should havecolor_group,colors- wherecolor_groupshould have 'shade' andname- each color incolorsshould havergbandhex
- so each item should have
- each option should have
- each decorator should have
I want to use symfony assertions to validate that json, and all is more or less straightforward except that rule where depends on atype I have different rules... I do not know how to do it right, I found that I can use expression or callback assertion but in both case it showing how to validate object but not a array.
Here is what I have:
new Assert\Collection(
[
'allowExtraFields' => true,
'fields' => [
'id' => [
new Assert\Required(),
new Assert\Type(['type' => 'integer']),
],
'decorations' => new Assert\All(
[
new Assert\Collection(
[
'allowExtraFields' => true,
'fields' => [
'id' => [
new Assert\Required(),
new Assert\Type(['type' => 'integer']),
],
'options' => new Assert\All(
[
'type' => [
new Assert\Required(),
new Assert\Type(['type' => 'string']),
],
'label' => [
new Assert\Required(),
new Assert\Type(['type' => 'string']),
],
'items' => new Assert\All(
[
new Assert\Collection(
[
'allowExtraFields' => true,
'fields' => [
// label is required for all types
'label' => [
new Assert\Required(),
new Assert\Type(['type' => 'string']),
]
// here I should add constraints for colors, if type equal to "color", but do not know how to make that if/else statement...
]
]
)
]
)
]
)
]
]
)
]
)
]
]
);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

