public function PromotionOrderProcessor::preprocess in Commerce Core 8.2
Preprocesses an order.
Parameters
\Drupal\commerce_order\Entity\OrderInterface $order: The order.
Overrides OrderPreprocessorInterface::preprocess
File
- modules/
promotion/ src/ PromotionOrderProcessor.php, line 47
Class
- PromotionOrderProcessor
- Applies promotions to orders during the order refresh process.
Namespace
Drupal\commerce_promotionCode
public function preprocess(OrderInterface $order) {
// Collect the promotion adjustments, to give promotions a chance to clear
// any potential modifications made to the order prior to refreshing it.
$promotion_ids = [];
foreach ($order
->collectAdjustments([
'promotion',
]) as $adjustment) {
if (empty($adjustment
->getSourceId())) {
continue;
}
$promotion_ids[] = $adjustment
->getSourceId();
}
// Additionally, promotions may have altered the order without actually
// adding promotion adjustments to the order, in this case, we need to
// inspect the order item data to see if arbitrary data was stored by
// promotion offers.
// This will eventually need to be replaced by a proper solution at some
// point once we have a more reliable way to figure out what the applied
// promotions are.
foreach ($order
->getItems() as $order_item) {
if ($order_item
->get('data')
->isEmpty()) {
continue;
}
$data = $order_item
->get('data')
->first()
->getValue();
foreach ($data as $key => $value) {
$key_parts = explode(':', $key);
// Skip order item data keys that are not starting by
// "promotion:<promotion_id>".
if (count($key_parts) === 1 || $key_parts[0] !== 'promotion' || !is_numeric($key_parts[1])) {
continue;
}
$promotion_ids[] = $key_parts[1];
}
}
// No promotions were found, stop here.
if (!$promotion_ids) {
return;
}
$promotion_ids = array_unique($promotion_ids);
/** @var \Drupal\commerce_promotion\PromotionStorageInterface $promotion_storage */
$promotion_storage = $this->entityTypeManager
->getStorage('commerce_promotion');
$promotions = $promotion_storage
->loadMultiple($promotion_ids);
/** @var \Drupal\commerce_promotion\Entity\PromotionInterface $promotion */
foreach ($promotions as $promotion) {
$promotion
->clear($order);
}
}