public function DonateOrderProcessor::process in Commerce Donate 8
Processes an order.
Parameters
\Drupal\commerce_order\Entity\OrderInterface $order: The order.
Overrides OrderProcessorInterface::process
File
- src/
DonateOrderProcessor.php, line 63
Class
- DonateOrderProcessor
- Adjust Currency of Donation when Order Changes currency.
Namespace
Drupal\commerce_donateCode
public function process(OrderInterface $order) {
// Try to find an existing order item.
foreach ($order
->getItems() as $order_item) {
if ($order_item
->bundle() == 'donation') {
$donation_order_item = $order_item;
break;
}
}
if (isset($donation_order_item)) {
// Get order total.
$total = $order
->getTotalPrice();
// Get main currency.
$resolved_currency = $this->currentCurrency
->getCurrency();
// This is used only to ensure that order have resolved currency.
// In combination with check on order load we can ensure that currency is
// same accross entire order.
// This solution provides avoiding constant recalculation
// on order load event on currency switch (if we don't explicitly set
// currency for total price when we switch currency.
// @see \Drupal\commerce_currency_resolver\EventSubscriber\OrderCurrencyRefresh
if ($total
->getCurrencyCode() !== $resolved_currency && $this
->shouldCurrencyRefresh($order)) {
$amount = $donation_order_item
->getUnitPrice()
->getNumber();
$donation_order_item->unit_price = [
'number' => $amount,
'currency_code' => $resolved_currency,
];
$currency_formatter = \Drupal::service('commerce_price.currency_formatter');
$amount_label = $currency_formatter
->format($amount, $resolved_currency);
$donation_order_item->title = t('@amount donation', [
'@amount' => $amount_label,
]);
$donation_order_item
->save();
// Save order.
$order
->save();
}
}
}