You are here

function commerce_coupon_commerce_discount_rule_build in Commerce Coupon 7.2

Implements hook_commerce_discount_rule_build().

File

./commerce_coupon.module, line 517
Provides coupon functionality for Drupal Commerce.

Code

function commerce_coupon_commerce_discount_rule_build($rule, $discount) {
  $discount_wrapper = entity_metadata_wrapper('commerce_discount', $discount);

  // Cache the discount's coupon count so that calls to it during checkout don't
  // have to.
  commerce_coupon_cache_coupon_count($discount);

  // Determine whether the discount has coupon references.
  if ($discount_wrapper->coupon_count
    ->value()) {

    // Product level discounts must pass the line item's order.
    $map = array(
      'order_discount' => 'commerce-order',
      'product_discount' => 'commerce-line-item:order',
    );
    if (isset($map[$discount->type])) {
      $rule
        ->condition('commerce_coupon_discount_coupon_codes_exist_on_order', array(
        'commerce_order:select' => $map[$discount->type],
        'commerce_discount' => $discount->name,
      ));

      // If this discount uses the multi strategy we need a different structure.
      // Get all coupons related to this discount and apply the discount action
      // for every coupon.
      if ($discount->type == 'order_discount' && !empty($discount->commerce_coupon_strategy) && $discount_wrapper->commerce_coupon_strategy
        ->value() == 'multi') {

        // Fetch the existing actions to wrap them later into a loop.
        $existing_actions = $rule
          ->actions();
        $rule
          ->action('commerce_coupon_discount_get_coupons_list', array(
          'commerce_order:select' => $map[$discount->type],
          'commerce_discount' => $discount->name,
          'weight' => -1,
        ));
        $coupon_loop = rules_loop(array(
          'list:select' => 'discount_coupons',
          'item:var' => 'coupon',
          'item:label' => 'Coupon',
        ));
        $coupon_loop
          ->setParent($rule);
        foreach ($existing_actions as $existing_action) {
          $existing_action
            ->setParent($coupon_loop);
        }
      }
    }
  }
}