You are here

public function PriceCalculator::calculate in Commerce Core 8.2

Calculates a purchasable entity's price.

Parameters

\Drupal\commerce\PurchasableEntityInterface $purchasable_entity: The purchasable entity.

string $quantity: The quantity.

\Drupal\commerce\Context $context: The context.

string[] $adjustment_types: The adjustment types to include in the calculated price. Examples: fee, promotion, tax.

Return value

\Drupal\commerce_order\PriceCalculatorResult The result.

Overrides PriceCalculatorInterface::calculate

File

modules/order/src/PriceCalculator.php, line 105

Class

PriceCalculator

Namespace

Drupal\commerce_order

Code

public function calculate(PurchasableEntityInterface $purchasable_entity, $quantity, Context $context, array $adjustment_types = []) {
  $resolved_price = $this->chainPriceResolver
    ->resolve($purchasable_entity, $quantity, $context);
  $processors = [];
  foreach ($adjustment_types as $adjustment_type) {
    $processors = array_merge($processors, $this
      ->getProcessors($adjustment_type));
  }
  if (empty($adjustment_types) || empty($processors)) {
    return new PriceCalculatorResult($resolved_price, $resolved_price);
  }

  /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
  $order_item_storage = $this->entityTypeManager
    ->getStorage('commerce_order_item');
  $order_item = $order_item_storage
    ->createFromPurchasableEntity($purchasable_entity);
  $order_item
    ->setUnitPrice($resolved_price);
  $order_item
    ->setQuantity($quantity);
  $order_type_id = $this->chainOrderTypeResolver
    ->resolve($order_item);
  $order = $this
    ->prepareOrder($order_type_id, $context);
  $order_item->order_id = $order;
  $order
    ->setItems([
    $order_item,
  ]);

  // Allow each selected processor to add its adjustments.
  foreach ($processors as $processor) {
    $processor
      ->process($order);
  }
  $calculated_price = $order_item
    ->getAdjustedTotalPrice();
  $adjustments = $order_item
    ->getAdjustments();
  $adjustments = $this->adjustmentTransformer
    ->processAdjustments($adjustments);
  return new PriceCalculatorResult($calculated_price, $resolved_price, $adjustments);
}