function commerce_discount_add_price_component in Commerce Discount 7
Adds 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).
5 calls to commerce_discount_add_price_component()
- commerce_discount_add_line_item in ./
commerce_discount.rules.inc - Creates a discount line item on the provided order.
- commerce_discount_fixed_amount in ./
commerce_discount.rules.inc - Rules action: Apply fixed amount discount.
- commerce_discount_free_products in ./
commerce_discount.rules.inc - Rules action: Apply free bonus products discount.
- commerce_discount_percentage in ./
commerce_discount.rules.inc - Rules action: Apply percentage discount.
- _commerce_discount_add_shipping_discount_price_component in ./
commerce_discount.rules.inc - Helper function for the shipping discount rules action.
File
- ./
commerce_discount.rules.inc, line 1395 - Rules integration for the Commerce Discount module.
Code
function commerce_discount_add_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();
$current_amount = $unit_price['amount'];
// Currencies don't match, abort.
if ($discount_amount['currency_code'] != $unit_price['currency_code']) {
return;
}
// Calculate the updated amount and create a price array representing the
// difference between it and the current amount.
$discount_amount['amount'] = commerce_round(COMMERCE_ROUND_HALF_UP, $discount_amount['amount']);
$updated_amount = $current_amount + $discount_amount['amount'];
$difference = array(
'amount' => $discount_amount['amount'],
'currency_code' => $discount_amount['currency_code'],
'data' => array(
'discount_name' => $discount_name,
'discount_component_title' => empty($component_title) ? t('Discount') : $component_title,
),
);
// Set the new unit price.
$line_item_wrapper->commerce_unit_price->amount = $updated_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, $difference, TRUE, TRUE);
}