I'd like to have the possibility to register variables in a loop and use them later in the parent scope.
A loop is often used to process variables, thus, in my eyes, it's crucial to be able to provide the processed variables back to the parent scope.
I tried to solve that by attached patch but I'm sure I hadn't considered all cases and there is a smarter way to do it.
Would be great if we could work on this :)

p.s. maybe we could introduce an setting to configure, if the loop has to register the variables back to the parent scope.

Comments

fago’s picture

Component: Rules Core » Rules Engine

Hm, but if you define a new variable during the loop, it would be defined multiple times. So which variable should be provided then? Perhaps, you could provide a use case for that?

As work-a-round it should be possible to define a variable before going into the loop.

das-peter’s picture

Thanks for your feedback fago.
Use case is to find e.g. the biggest integer to use them later on:
Current commerce project has fees which apply based on the longest duration of a product - I iterate over all line items in the cart, add dedicated fees and retrieve the duration of each line item product, if the value is bigger as the already stored one I replace the value in the variable.

Oh wait - now as I write this down I see an issue with the patch...
*patch rework in progress*

Ok, now the code updates the variables earlier so that the updated values are available in each iteration. And only variables which origin from the parent scope are registered back.

fago’s picture

>And only variables which origin from the parent scope are registered back.

Oh, now I see the problem. If you change a not-wrapped variable, the changes would be lost. I agree that those changes should appear in the parent state though.

+      $parent_vars = array_intersect(array_keys($state->variables), array_keys($state2->variables));
+      foreach($parent_vars as $var_key) {
+        $state->variables[$var_key] = $state2->variables[$var_key];
+      }

The parent vars must be the same as $state->variables, as $state2 contains all parent vars anyway. Then you are missing a space after foreach.
Also, let's add a short comment explaining what we are doing here.

das-peter’s picture

Status: Needs work » Needs review
StatusFileSize
new627 bytes

thanks for your feedback - patch updated.

fago’s picture

Status: Needs review » Fixed

thanks, committed.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.