public function OrderFixedAmountOff::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/ OrderFixedAmountOff.php, line 27
Class
- OrderFixedAmountOff
- Provides the fixed amount off offer for orders.
Namespace
Drupal\commerce_promotion\Plugin\Commerce\PromotionOfferCode
public function apply(EntityInterface $entity, PromotionInterface $promotion) {
$this
->assertEntity($entity);
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $entity;
$subtotal_price = $order
->getSubTotalPrice();
$amount = $this
->getAmount();
if ($subtotal_price
->getCurrencyCode() != $amount
->getCurrencyCode()) {
return;
}
$total_price = $order
->getTotalPrice();
// The promotion amount can't be larger than the total, to avoid
// potentially having a negative order total.
if ($total_price && $amount
->greaterThan($total_price)) {
$amount = $total_price;
}
// Skip applying the promotion if there's no amount to discount.
if ($amount
->isZero()) {
return;
}
// Split the amount between order items.
$amounts = $this->splitter
->split($order, $amount);
foreach ($order
->getItems() as $order_item) {
if (isset($amounts[$order_item
->id()])) {
$order_item
->addAdjustment(new Adjustment([
'type' => 'promotion',
'label' => $promotion
->getDisplayName() ?: $this
->t('Discount'),
'amount' => $amounts[$order_item
->id()]
->multiply('-1'),
'source_id' => $promotion
->id(),
]));
}
}
}