function commerce_discount_remove_discount_components in Commerce Discount 7
Remove discount components from a given price and recalculate the total.
Parameters
object $price_wrapper: Wrapped commerce price.
array $discount_types_to_remove: An array of discount type strings to remove.
Return value
bool TRUE if at least one price component has been removed, FALSE otherwise.
2 calls to commerce_discount_remove_discount_components()
- commerce_discount_commerce_cart_order_refresh in ./
commerce_discount.module - Implements hook_commerce_cart_order_refresh().
- commerce_discount_remove_discount_components_on_products in ./
commerce_discount.rules.inc - Rules action: Remove discount components on product line items.
File
- ./
commerce_discount.module, line 103 - Defines the discount and discount offer entities, bundles and functionality.
Code
function commerce_discount_remove_discount_components($price_wrapper, $discount_types_to_remove = array(
'order_discount',
)) {
$price = $price_wrapper
->value();
// If there are no price or components, there is nothing to remove.
if (!$price || empty($price['data']['components'])) {
return FALSE;
}
$data = (array) $price['data'] + array(
'components' => array(),
);
$component_removed = FALSE;
// Remove price components belonging to order discounts.
foreach ($data['components'] as $key => $component) {
$remove = FALSE;
// Remove all discount components.
if (!empty($component['price']['data']['discount_name'])) {
$discount_name = $component['price']['data']['discount_name'];
$discount = entity_load_single('commerce_discount', $discount_name);
if (!$discount || in_array($discount->type, $discount_types_to_remove)) {
$remove = TRUE;
}
}
elseif ($component['name'] != 'base_price') {
// As long as the component is neither base price nor discount, allow
// other modules to say whether it gets reset. This is so that discounts
// can apply against a price that has been stripped of components from
// modules that need to apply against a post-discount price.
drupal_alter('commerce_discount_remove_price_component', $component, $remove);
}
if ($remove) {
unset($data['components'][$key]);
$component_removed = TRUE;
}
}
// Don't alter the price components if no components were removed.
if (!$component_removed) {
return FALSE;
}
// Properly re-key the components array.
$data['components'] = array_values($data['components']);
// Re-save the price without the discounts (if existed).
$price_wrapper->data
->set($data);
// Re-set the total price.
$total = commerce_price_component_total($price_wrapper
->value());
$price_wrapper->amount = $total['amount'];
return TRUE;
}