You are here

function _commerce_coupon_update_orders_multipass in Commerce Coupon 7.2

Update four orders at a time.

Parameters

array $sandbox: A persistent context store for batch updates.

1 call to _commerce_coupon_update_orders_multipass()
commerce_coupon_update_7200 in ./commerce_coupon.install
Upgrade a Coupons 1.x site to 2.x. MAKE A BACKUP BEFORE DOING THIS.

File

includes/commerce_coupon.update.inc, line 145
1.x to 2.x update coverage.

Code

function _commerce_coupon_update_orders_multipass(&$sandbox, $drush) {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'commerce_order')
    ->fieldCondition('commerce_coupon_order_reference', 'target_id', 'NULL', '!=');
  if (!isset($sandbox['orders']['progress'])) {
    $sandbox['orders']['progress'] = 0;
    $sandbox['orders']['current_id'] = 0;

    // Calculate the number of orders to need to be processed.
    $count_query = clone $query;
    $sandbox['orders']['max'] = $count_query
      ->count()
      ->execute();
  }
  $results = $query
    ->propertyCondition('order_id', $sandbox['orders']['current_id'], '>')
    ->range(0, COMMERCE_COUPON_ORDER_IMPORT_RATE)
    ->propertyOrderBy('order_id', 'ASC')
    ->execute();
  if (!empty($results['commerce_order'])) {
    $order_ids = $results['commerce_order'];
    $orders = commerce_order_load_multiple(array_keys($results['commerce_order']));
    foreach ($orders as $order) {
      $original_order = clone $order;

      // Transfer coupon reference to the new field.
      $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
      if ($order_wrapper->commerce_coupon_order_reference
        ->value()) {
        $order_wrapper->commerce_coupons = $order_wrapper->commerce_coupon_order_reference
          ->value();

        // Allow modules to alter the order before it is saved.
        drupal_alter('commerce_coupon_update_order_pre_update', $original_order, $order);
        if (module_exists('commerce_coupon_usage')) {
          $statuses = array_merge(commerce_order_statuses(array(
            'state' => 'pending',
          )), commerce_order_statuses(array(
            'state' => 'completed',
          )));

          // If the order is complete or pending, record a use of the coupon.
          if (in_array($order->status, array_keys($statuses))) {
            commerce_coupon_usage_record_usage($order);
          }
        }
        $order_wrapper
          ->save();
      }
      $sandbox['orders']['progress']++;
      $sandbox['orders']['current_id'] = $order->order_id;
    }
    if ($drush) {
      drush_print(t('Processed @n orders', array(
        '@n' => count($order_ids),
      )));
    }
  }
  else {
    $sandbox['orders']['#finished'] = 1;
  }
  $sandbox['orders']['#finished'] = empty($sandbox['orders']['max']) ? 1 : $sandbox['orders']['progress'] / $sandbox['orders']['max'];
}