OrderItemPercentageOff.php in Commerce Core 8.2
File
modules/promotion/src/Plugin/Commerce/PromotionOffer/OrderItemPercentageOff.php
View source
<?php
namespace Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer;
use Drupal\commerce_order\Adjustment;
use Drupal\commerce_promotion\Entity\PromotionInterface;
use Drupal\Core\Entity\EntityInterface;
class OrderItemPercentageOff extends OrderItemPromotionOfferBase {
use PercentageOffTrait;
public function apply(EntityInterface $entity, PromotionInterface $promotion) {
$this
->assertEntity($entity);
$order_item = $entity;
$percentage = $this
->getPercentage();
if ($this->configuration['display_inclusive']) {
$adjusted_unit_price = $order_item
->getAdjustedUnitPrice([
'promotion',
]);
if ($adjusted_unit_price
->isZero()) {
return;
}
$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);
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'],
]));
}
}