You are here

function commerce_order_update_7100 in Commerce Core 7

Loads and resaves all the products on the site, updating the default price field to have proper component price amount values.

File

modules/order/commerce_order.install, line 226

Code

function commerce_order_update_7100(&$sandbox) {

  // Ensure there are no stale prices in the field cache.
  field_cache_clear();

  // Establish the progress variables.
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['current_product_id'] = 0;
    $sandbox['max'] = db_query("SELECT COUNT(DISTINCT product_id) FROM {commerce_product}")
      ->fetchField();
  }

  // Load the next 50 products.
  $products = db_select('commerce_product', 'cp')
    ->fields('cp', array(
    'product_id',
  ))
    ->condition('product_id', $sandbox['current_product_id'], '>')
    ->range(0, 50)
    ->orderBy('product_id', 'ASC')
    ->execute();

  // Loop over the products, loading, adjusting, and resaving each one.
  foreach ($products as $product) {
    $product = commerce_product_load($product->product_id);

    // If the commerce_price field has a components array, multiply its price
    // amounts by the proper value for its currency.
    if (!empty($product->commerce_price)) {
      foreach ($product->commerce_price as $langcode => &$data) {
        foreach ($data as $delta => &$item) {
          if (!empty($item['data']['components'])) {
            foreach ($item['data']['components'] as $key => &$component) {
              $component['price']['amount'] = commerce_currency_decimal_to_amount($component['price']['amount'], $component['price']['currency_code'], FALSE);
            }
          }
        }
      }
    }
    commerce_product_save($product);
    $sandbox['progress']++;
    $sandbox['current_product_id'] = $product->product_id;
  }
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];
  return t('All products have been loaded and saved with updated price component arrays.');
}