You are here

function commerce_price_table_sum_quantities in Commerce Price Table 7

Rules callback: provides a combined product sum variable in a rule based on all line items sharing the same product display as the given one.

File

./commerce_price_table.rules.inc, line 129

Code

function commerce_price_table_sum_quantities($line_item_wrapper) {
  $sum = 0;

  // If the line item does not have an ID, it is being used to calculate a price
  // on a product display. Return its quantity.
  if (empty($line_item_wrapper
    ->value()->line_item_id)) {
    return array(
      'combined_product_sum' => $line_item_wrapper->quantity
        ->value(),
    );
  }

  // Loop over all line items on the order...
  foreach ($line_item_wrapper->order->commerce_line_items as $delta => $target_line_item_wrapper) {
    if (!in_array($target_line_item_wrapper->type
      ->value(), commerce_product_line_item_types())) {
      continue;
    }

    // If the current target line item references the same product as the
    // original one, include its quantity in the sum.
    if ($line_item_wrapper->commerce_product
      ->raw() == $target_line_item_wrapper->commerce_product
      ->raw()) {
      $sum += $target_line_item_wrapper->quantity
        ->value();
      continue;
    }

    // If the current target line item shares the same display context as the
    // original one, include its quantity in the sum.
    $source_data = $line_item_wrapper
      ->value()->data;
    $target_data = $target_line_item_wrapper
      ->value()->data;
    if (empty($source_data['context']) || empty($target_data['context'])) {
      continue;
    }
    if ($source_data['context']['product_ids'] == $target_data['context']['product_ids']) {

      // Include special checking for product IDs derived from reference fields.
      if ($source_data['context']['product_ids'] == 'entity') {
        if ($source_data['context']['entity'] == $target_data['context']['entity']) {
          $sum += $target_line_item_wrapper->quantity
            ->value();
        }
      }
      else {
        $sum += $target_line_item_wrapper->quantity
          ->value();
      }
    }
  }
  return array(
    'combined_product_sum' => $sum,
  );
}