You are here

function commerce_product_pre_calculation_rule_keys in Commerce Core 7

Returns an array of rule keys used for pre-calculating product sell prices.

Rule keys represent every possible combination of rules that might alter any given product sell price. If no valid rules exist, an empty array is returned.

2 calls to commerce_product_pre_calculation_rule_keys()
commerce_product_batch_pre_calculate_sell_prices in modules/product_pricing/commerce_product_pricing.module
Sets a batch operation to pre-calculate product sell prices.
commerce_product_pre_calculate_sell_prices in modules/product_pricing/commerce_product_pricing.module
Pre-calculates sell prices for qualifying products based on valid rule configurations on the "Calculating product sell price" event.

File

modules/product_pricing/commerce_product_pricing.module, line 205
Enables Rules based product sell price calculation for dynamic product pricing.

Code

function commerce_product_pre_calculation_rule_keys() {
  static $rule_keys = NULL;
  if (is_null($rule_keys)) {

    // Load the sell price calculation event.
    $event = rules_get_cache('event_commerce_product_calculate_sell_price');

    // Build an array of the names of all rule configurations that qualify for
    // dynamic pre-calculation.
    $rule_names = array();
    foreach ($event as $rule) {
      if (commerce_product_valid_pre_calculation_rule($rule)) {
        $rule_names[] = $rule->name;
      }
    }

    // Sort to ensure the names are always in alphabetical order.
    sort($rule_names);

    // Using the array of names, generate an array that contains keys for every
    // possible combination of these Rules applying (i.e. conditions all passing).
    $rule_keys = array();

    // First find the maximum number of combinations as a power of two.
    $max = pow(2, count($rule_names));

    // Loop through each combination expressed as an integer.
    for ($i = 0; $i < $max; $i++) {

      // Convert the integer to a string binary representation, reverse it (so the
      // first bit is on the left instead of right), and split it into an array
      // with each bit as its own value.
      $bits = str_split(strrev(sprintf('%0' . count($rule_names) . 'b', $i)));

      // Create a key of underscore delimited Rule IDs by assuming a 1 means the
      // Rule ID in the $rule_ids array with the same key as the bit's position in
      // the string should be assumed to have applied.
      $key = implode('|', array_intersect_key($rule_names, array_intersect($bits, array(
        '1',
      ))));
      $rule_keys[] = $key;
    }
  }
  return $rule_keys;
}