Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joelpittet/f002bc6a92cb3669820e to your computer and use it in GitHub Desktop.
Save joelpittet/f002bc6a92cb3669820e to your computer and use it in GitHub Desktop.
diff --git a/commerce_discount.module b/commerce_discount.module
index c5e82bf..3b41161 100644
--- a/commerce_discount.module
+++ b/commerce_discount.module
@@ -6,12 +6,44 @@
* their bundles, and all surrounding functionality (API, UI).
*/
+function commerce_discount_line_items_hash($wrapper) {
+ $line_items = $wrapper->commerce_line_items->value();
+ return md5(json_encode($line_items));
+
+ // Get the line item types to apply the discount to.
+ $line_item_types = variable_get('commerce_discount_line_item_types', array('product' => 'product'));
+ $line_item_types = array_filter($line_item_types);
+ // Loop through each line item, get it's value in an array and hash the array.
+ $line_items = array();
+ foreach ($wrapper->commerce_line_items as $delta => $wrapper_line_item) {
+ $line_item_type = $wrapper_line_item->getBundle();
+ if (isset($line_item_types[$line_item_type])) {
+ $line_items[] = $wrapper_line_item->value();
+ }
+ }
+
+ return md5(json_encode($line_items));
+}
+
/**
* Implements hook_commerce_cart_order_refresh().
*
* Remove any existing commerce discount line item.
*/
function commerce_discount_commerce_cart_order_refresh($wrapper) {
+ $order = $wrapper->value();
+ if (!empty($order->data['commerce_discount_line_items_hash'])) {
+ $original_line_items_hash = $order->data['commerce_discount_line_items_hash'];
+ $original_line_items = $order->data['commerce_discount_original_line_items'];
+ $line_items = json_encode($wrapper->commerce_line_items->value(), JSON_PRETTY_PRINT);
+
+ // Check if line items have changed before doing any modifications.
+ $updated_line_items_hash = commerce_discount_line_items_hash($wrapper);
+ if ($updated_line_items_hash === $original_line_items_hash) {
+ return;
+ }
+ }
+
$line_items_to_delete = array();
$cloned_line_items = array();
// Remove all discount references from the order.
@@ -75,7 +107,11 @@ function commerce_discount_commerce_cart_order_refresh($wrapper) {
commerce_line_item_delete_multiple($line_items_to_delete);
// Re-add all applicable discount price components and/or line items.
- rules_invoke_event('commerce_discount_order', $wrapper->value());
+ rules_invoke_event('commerce_discount_order', $order);
+
+ // Re-hash the line items.
+ $order->data['commerce_discount_original_line_items'] = json_encode($wrapper->commerce_line_items->value(), JSON_PRETTY_PRINT);
+ $order->data['commerce_discount_line_items_hash'] = commerce_discount_line_items_hash($wrapper);
}
/**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment