Skip to content

Commit

Permalink
Merge branch 'next-11653/fix-cart-rule-loading' into 'master'
Browse files Browse the repository at this point in the history
NEXT-11653 - Fix priority in cart and rule loading

See merge request shopware/6/product/platform!3587
  • Loading branch information
OliverSkroblin committed Oct 27, 2020
2 parents 58f8c55 + e1b6e8c commit b76322f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
28 changes: 21 additions & 7 deletions src/Core/Checkout/Cart/CartRuleLoader.php
Expand Up @@ -12,7 +12,7 @@
class CartRuleLoader
{
public const CHECKOUT_RULE_LOADER_CACHE_KEY = 'all-rules';
private const MAX_ITERATION = 5;
private const MAX_ITERATION = 7;

/**
* @var CartPersisterInterface
Expand Down Expand Up @@ -84,29 +84,43 @@ private function load(SalesChannelContext $context, Cart $cart, CartBehavior $be
{
$rules = $this->loadRules($context->getContext());

// save all rules for later usage
$all = $rules;

// update rules in current context
$context->setRuleIds($rules->getIds());

$iteration = 1;

// start first cart calculation to have all objects enriched
$cart = $this->processor->process($cart, $context, $behaviorContext);

do {
$compare = $cart;

if ($iteration > self::MAX_ITERATION) {
break;
}

//find rules which matching current cart and context state
// filter rules which matches to current scope
$rules = $rules->filterMatchingRules($cart, $context);

//place rules into context for further usages
// update matching rules in context
$context->setRuleIds($rules->getIds());

//recalculate cart for new context rules
$new = $this->processor->process($cart, $context, $behaviorContext);
// calculate cart again
$cart = $this->processor->process($cart, $context, $behaviorContext);

$recalculate = $this->cartChanged($cart, $new);
// check if the cart changed, in this case we have to recalculate the cart again
$recalculate = $this->cartChanged($cart, $compare);

$cart = $new;
// check if rules changed for the last calculated cart, in this case we have to recalculate
$ruleCompare = $all->filterMatchingRules($cart, $context);

if (!$rules->equals($ruleCompare)) {
$recalculate = true;
$rules = $ruleCompare;
}

++$iteration;
} while ($recalculate);
Expand Down
15 changes: 15 additions & 0 deletions src/Core/Content/Rule/RuleCollection.php
Expand Up @@ -34,6 +34,21 @@ public function sortByPriority(): void
});
}

public function equals(RuleCollection $rules): bool
{
if ($this->count() !== $rules->count()) {
return false;
}

foreach ($this->elements as $element) {
if (!$rules->has($element->getId())) {
return false;
}
}

return true;
}

public function getApiAlias(): string
{
return 'rule_collection';
Expand Down

0 comments on commit b76322f

Please sign in to comment.