You are here

function commerce_discount_set_price_component in Commerce Discount 7

Sets a discount price component to the provided line item.

Parameters

EntityDrupalWrapper $line_item_wrapper: The wrapped line item entity.

string $discount_name: The name of the discount being applied.

array $discount_amount: The discount amount price array (amount, currency_code).

1 call to commerce_discount_set_price_component()
commerce_discount_set_existing_line_item_price in ./commerce_discount.rules.inc
Updates the unit price of the discount line item matching the named discount.

File

./commerce_discount.rules.inc, line 1454
Rules integration for the Commerce Discount module.

Code

function commerce_discount_set_price_component(EntityDrupalWrapper $line_item_wrapper, $discount_name, $discount_amount) {
  $unit_price = commerce_price_wrapper_value($line_item_wrapper, 'commerce_unit_price', TRUE);
  $discount_wrapper = entity_metadata_wrapper('commerce_discount', $discount_name);
  $component_title = $discount_wrapper->component_title
    ->value();

  // Currencies don't match, abort.
  if ($discount_amount['currency_code'] != $unit_price['currency_code']) {
    return;
  }
  $discount_amount['amount'] = commerce_round(COMMERCE_ROUND_HALF_UP, $discount_amount['amount']);
  $discount_amount['data'] = array(
    'discount_name' => $discount_name,
    'discount_component_title' => empty($component_title) ? 'discount' : $component_title,
  );

  // Set the new unit price.
  $line_item_wrapper->commerce_unit_price->amount = $discount_amount['amount'];

  // Add the discount amount as a price component.
  $unit_price = commerce_price_wrapper_value($line_item_wrapper, 'commerce_unit_price', TRUE);
  $type = empty($component_title) ? 'discount' : check_plain('discount|' . $discount_name);
  $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add($unit_price, $type, $discount_amount, TRUE, TRUE);
}