You are here

protected function BuyXGetY::calculateExpectedGetQuantity in Commerce Core 8.2

Calculates the expected get quantity.

Parameters

array $buy_quantities: An array of buy quantities.

\Drupal\commerce_order\Entity\OrderItemInterface $order_item: The order item.

Return value

string The expected get quantity.

1 call to BuyXGetY::calculateExpectedGetQuantity()
BuyXGetY::apply in modules/promotion/src/Plugin/Commerce/PromotionOffer/BuyXGetY.php
Applies the offer to the given entity.

File

modules/promotion/src/Plugin/Commerce/PromotionOffer/BuyXGetY.php, line 604

Class

BuyXGetY
Provides the "Buy X Get Y" offer for orders.

Namespace

Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer

Code

protected function calculateExpectedGetQuantity(array $buy_quantities, OrderItemInterface $order_item) {
  $expected_get_quantity = '0';

  // Ensure that any possible "get" quantity already in the order is always
  // processed last.
  if (!$order_item
    ->isNew()) {
    if (isset($buy_quantities[$order_item
      ->id()])) {
      $quantity = $buy_quantities[$order_item
        ->id()];
      unset($buy_quantities[$order_item
        ->id()]);
      $buy_quantities[$order_item
        ->id()] = $quantity;
    }
  }
  $i = 0;
  while (!empty($buy_quantities)) {
    $this
      ->sliceQuantities($buy_quantities, $this->configuration['buy_quantity']);
    $expected_get_quantity = Calculator::add($expected_get_quantity, $this->configuration['get_quantity']);

    // Determine whether the offer reached its limit.
    if ($this->configuration['offer_limit'] == ++$i) {
      break;
    }

    // If the "get" purchasable entity is already in the order, we need to
    // ensure that the already discounted quantity is not counted towards the
    // buy quantities.
    if (!$order_item
      ->isNew()) {
      $buy_quantities = $this
        ->removeQuantities($buy_quantities, [
        $order_item
          ->id() => $this->configuration['get_quantity'],
      ]);
    }
    if (array_sum($buy_quantities) < $this->configuration['buy_quantity']) {
      break;
    }
  }
  return $expected_get_quantity;
}