You are here

public function OrderItemPercentageOff::apply in Commerce Core 8.2

Applies the offer to the given entity.

Parameters

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

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

Overrides PromotionOfferInterface::apply

File

modules/promotion/src/Plugin/Commerce/PromotionOffer/OrderItemPercentageOff.php, line 25

Class

OrderItemPercentageOff
Provides the percentage off offer for order items.

Namespace

Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer

Code

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

  /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
  $order_item = $entity;
  $percentage = $this
    ->getPercentage();
  if ($this->configuration['display_inclusive']) {

    // First, get the adjusted unit price to ensure the order item is not
    // already fully discounted.
    $adjusted_unit_price = $order_item
      ->getAdjustedUnitPrice([
      'promotion',
    ]);

    // The adjusted unit price is already reduced to 0, no need to continue
    // further.
    if ($adjusted_unit_price
      ->isZero()) {
      return;
    }

    // Display-inclusive promotions must first be applied to the unit price.
    $amount = $adjusted_unit_price
      ->multiply($percentage);
    $amount = $this->rounder
      ->round($amount);
    $new_unit_price = $order_item
      ->getUnitPrice()
      ->subtract($amount);
    $order_item
      ->setUnitPrice($new_unit_price);
    $adjustment_amount = $amount
      ->multiply($order_item
      ->getQuantity());
  }
  else {
    $adjusted_total_price = $order_item
      ->getAdjustedTotalPrice([
      'promotion',
    ]);
    $adjustment_amount = $adjusted_total_price
      ->multiply($percentage);
  }
  $adjustment_amount = $this->rounder
    ->round($adjustment_amount);

  // Skip applying the promotion if there's no amount to discount.
  if ($adjustment_amount
    ->isZero()) {
    return;
  }
  $order_item
    ->addAdjustment(new Adjustment([
    'type' => 'promotion',
    'label' => $promotion
      ->getDisplayName() ?: $this
      ->t('Discount'),
    'amount' => $adjustment_amount
      ->multiply('-1'),
    'percentage' => $percentage,
    'source_id' => $promotion
      ->id(),
    'included' => $this->configuration['display_inclusive'],
  ]));
}