I have a list of products for which I generate prices according to simple rules I wrote as if statements, something like
if ($product[rarity] == 'Rare') { $price += 2 }
if ($product[foil]) { $price += $price * 0.1 }
if ($product[weight] >= 6 and $product[weight] < 11) { $price += $price * 0.2 }
if ($product[rarity] == 'Mythic' and $price < 0.7 ) { $price = 0.7 }
But because those rules are being changed very often and their amount rises with each day, I decided to store "rules" as JSON. This should also help me write some kind of UI for other users. My example JSON could look like this
{
"rules": [{
"name": "Add 2 to price if rarity is Rare",
"predicates": [{
"field": "rarity",
"operator": "==",
"value": "Rare"
}
],
"then": [{
"do": "add",
"value": "2"
}
]
}, {
"name": "Increase price by 20% if weight is between 6 and 11",
"predicates": [{
"field": "weight",
"operator": ">=",
"value": "6"
}, {
"field": "weight",
"operator": "<",
"value": "11"
}
],
"then": [{
"do": "add_percentage",
"value": "20"
}
]
}
]
}
I know how to read data from JSON but I have no idea how to generate dynamic if statements using it. I have found eval but I don't know if using it is a correct approach.
I will appreciate any help and tips
Aucun commentaire:
Enregistrer un commentaire