AvailabilityOrderProcessor.php in Commerce Core 8.2
File
modules/order/src/AvailabilityOrderProcessor.php
View source
<?php
namespace Drupal\commerce_order;
use Drupal\commerce\Context;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class AvailabilityOrderProcessor implements OrderProcessorInterface {
protected $availabilityManager;
protected $entityTypeManager;
public function __construct(AvailabilityManagerInterface $availability_manager, EntityTypeManagerInterface $entity_type_manager) {
$this->availabilityManager = $availability_manager;
$this->entityTypeManager = $entity_type_manager;
}
public function process(OrderInterface $order) {
$context = new Context($order
->getCustomer(), $order
->getStore());
$order_items_to_remove = [];
foreach ($order
->getItems() as $order_item) {
$purchased_entity = $order_item
->getPurchasedEntity();
if (!$purchased_entity) {
continue;
}
$availability_result = $this->availabilityManager
->check($order_item, $context);
if ($availability_result
->isUnavailable()) {
$order_items_to_remove[$order_item
->id()] = $order_item;
}
}
if (!$order_items_to_remove) {
return;
}
$order_item_storage = $this->entityTypeManager
->getStorage('commerce_order_item');
$order_item_ids = array_keys($order_items_to_remove);
$order
->get('order_items')
->filter(function ($item) use ($order_item_ids) {
return !in_array($item->target_id, $order_item_ids);
});
$order_item_storage
->delete($order_items_to_remove);
$order
->recalculateTotalPrice();
}
}