You are here

public function BuyXGetY::clear in Commerce Core 8.2

Allows an offer to clean up any modifications done to the given entity.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity.

\Drupal\commerce_promotion\Entity\PromotionInterface $promotion: THe parent promotion.

Overrides PromotionOfferBase::clear

File

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

Class

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

Namespace

Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer

Code

public function clear(EntityInterface $entity, PromotionInterface $promotion) {
  parent::clear($entity, $promotion);
  $this
    ->assertEntity($entity);

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $entity;

  // Check if we have any order item whose quantity has been changed by this
  // promotion, and subtract that amount. If the promotion still applies, the
  // necessary quantity will be added back in ::apply(). Order items that will
  // end up with a quantity of 0 will be removed from the order by
  // \Drupal\commerce_order\OrderRefresh::refresh().
  if ($this->configuration['get_auto_add']) {
    $promotion_data_key = "promotion:{$promotion->id()}:auto_add_quantity";
    $auto_add_order_items = array_filter($order
      ->getItems(), function (OrderItemInterface $order_item) use ($promotion_data_key) {
      return $order_item
        ->getData($promotion_data_key);
    });
    foreach ($auto_add_order_items as $order_item) {
      $new_quantity = Calculator::subtract($order_item
        ->getQuantity(), $order_item
        ->getData($promotion_data_key));
      $order_item
        ->setQuantity($new_quantity);
      $order_item
        ->unsetData($promotion_data_key);
    }
  }
}