public function PromotionSubscriber::onCalculate in Commerce Shipping 8.2
Applies the promotions.
Parameters
\Drupal\commerce_shipping\Event\ShippingRatesEvent $event: The event.
File
- src/
EventSubscriber/ PromotionSubscriber.php, line 63
Class
- PromotionSubscriber
- Applies display-inclusive promotions to the calculated shipping rates.
Namespace
Drupal\commerce_shipping\EventSubscriberCode
public function onCalculate(ShippingRatesEvent $event) {
$rates = $event
->getRates();
if (empty($rates)) {
return;
}
$shipping_method = $event
->getShippingMethod();
$shipment = $event
->getShipment();
$order = $shipment
->getOrder();
$promotions = $this
->getPromotions($order);
if (empty($promotions)) {
return;
}
// Clone the entities to avoid modifying the original data.
$fake_shipment = clone $shipment;
$fake_order = clone $order;
$fake_order
->set('shipments', [
$fake_shipment,
]);
// Re-fetch the shipment to acquire a reference.
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface[] $fake_shipments */
$fake_shipments = $fake_order
->get('shipments')
->referencedEntities();
$fake_shipment = reset($fake_shipments);
// Calculate the discounted amounts.
foreach ($rates as $rate) {
$shipping_method
->getPlugin()
->selectRate($fake_shipment, $rate);
$fake_shipment
->clearAdjustments();
foreach ($promotions as $promotion) {
if ($promotion
->applies($fake_order)) {
$promotion
->apply($fake_order);
}
}
$rate
->setAmount($fake_shipment
->getAmount());
}
}