You are here

public function OrderItemFixedAmountOff::apply in Commerce Currency Resolver 8

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 OrderItemFixedAmountOff::apply

File

src/Plugin/Commerce/PromotionOffer/OrderItemFixedAmountOff.php, line 23

Class

OrderItemFixedAmountOff
Provides the percentage off offer for order items with multicurrency support.

Namespace

Drupal\commerce_currency_resolver\Plugin\Commerce\PromotionOffer

Code

public function apply(EntityInterface $entity, PromotionInterface $promotion) {

  // Nothing to do. Go to parent.
  if (!$this
    ->shouldCurrencyRefresh($this
    ->getAmount()
    ->getCurrencyCode())) {
    return parent::apply($entity, $promotion);
  }
  $this
    ->assertEntity($entity);

  /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
  $order_item = $entity;
  $total_price = $order_item
    ->getTotalPrice();

  // Convert prices.
  $amount = $this
    ->getPrice($this
    ->getAmount());
  if ($this->configuration['display_inclusive']) {

    // Display-inclusive promotions must first be applied to the unit price.
    $unit_price = $order_item
      ->getUnitPrice();
    if ($amount
      ->greaterThan($unit_price)) {

      // Don't reduce the unit price past zero.
      $amount = $unit_price;
    }
    $new_unit_price = $unit_price
      ->subtract($amount);
    $order_item
      ->setUnitPrice($new_unit_price);
    $adjustment_amount = $amount
      ->multiply($order_item
      ->getQuantity());
    $adjustment_amount = $this->rounder
      ->round($adjustment_amount);
  }
  else {
    $adjustment_amount = $amount
      ->multiply($order_item
      ->getQuantity());
    $adjustment_amount = $this->rounder
      ->round($adjustment_amount);
    if ($adjustment_amount
      ->greaterThan($total_price)) {

      // Don't reduce the order item total price past zero.
      $adjustment_amount = $total_price;
    }
  }
  $order_item
    ->addAdjustment(new Adjustment([
    'type' => 'promotion',
    'label' => $promotion
      ->getDisplayName() ?: $this
      ->t('Discount'),
    'amount' => $adjustment_amount
      ->multiply('-1'),
    'source_id' => $promotion
      ->id(),
    'included' => $this->configuration['display_inclusive'],
  ]));
}