Is it a good idea to rely on the rule builder in a cart validator service (6.4.13.0)

Viewed 40

I build a functionality that forbids certain line items in the cart. E. g. some products are forbidden to be put into the cart for some customers. They are still allowed to see them. To identify the customers, who are allowed, I use the rule builder. So its usage is similar to the availability rule used in shipping methods. To exclude products from the cart I use a cart validator.

What I just experienced is, that the rules on a context are set by the CartRuleLoader. This service validates the cart to check rules against the cart. Now I have the issue, that on the first validation run (called from the CartRuleLoader) the context has a rule id in there that is not valid for the situation. Then the context rule ids are set and then the cart is later validated again, but it is now missing the rule id I look for in its context. It feels like it is wrong to rely on rule ids in cart validators. Are there any guidelines when you can rely on rule ids? Because I really want to make use of the rule builder there but it feels wrong.

1 Answers

As you already mentioned the CartRuleLoader loops the evaluation of rules (up to 7 times) and within these iterations it may change the rule IDs of the context. This is because a rule might lead to changed prices in the cart. If another rule is evaluating prices this might then change the result of its evaluation and so on. So you definitely have to await the end of these iterations. There is an event SalesChannelContextResolvedEvent that is dispatched with the context in its final state. Within a subscriber you could use this final set of rule ID and inject the CartService to validate the cart against the rules and eventually add errors to the cart.

Related