You are here

function _farm_livestock_update_7005_stage2 in farmOS 7

Update 7005 stage 2: Create group assets for each animal group term.

See also

farm_livestock_update_7005().

1 call to _farm_livestock_update_7005_stage2()
farm_livestock_update_7005 in modules/farm/farm_livestock/farm_livestock.install
Create group assets for each animal group term, assign animals to new group assets, convert egg logs to harvest logs, and remove old animal groups taxonomy and related features.

File

modules/farm/farm_livestock/farm_livestock.install, line 182
Farm livestock install file.

Code

function _farm_livestock_update_7005_stage2(&$sandbox) {

  // If we are not on stage 2, bail.
  if (empty($sandbox['stage']) || $sandbox['stage'] != 2) {
    return;
  }

  // Load the "Farm Animal Groups" vocabulary.
  $group_vocab = taxonomy_vocabulary_machine_name_load('farm_animal_groups');

  // Prepare to process this stage in batches.
  if (!isset($sandbox['stage2_progress'])) {
    $sandbox['stage2_progress'] = 0;
    $sandbox['stage2_max'] = db_query('SELECT COUNT(tid) FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY tid ASC', array(
      ':vid' => $group_vocab->vid,
    ))
      ->fetchField();
  }

  // Load the next batch of term IDs from the database.
  $limit = 25;
  $result = db_query_range('SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY tid ASC', $sandbox['stage2_progress'], $limit, array(
    ':vid' => $group_vocab->vid,
  ));
  $group_ids = array();
  foreach ($result as $row) {
    if (!empty($row->tid)) {
      $group_ids[] = $row->tid;
    }
  }

  // Iterate through the animal groups.
  foreach ($group_ids as $tid) {

    // Increment the progress.
    $sandbox['stage2_progress']++;

    // Load the term.
    $group_term = taxonomy_term_load($tid);

    // Create a new Group asset with the same name.
    $values = array(
      'name' => $group_term->name,
      'type' => 'group',
    );
    $group_asset = entity_create('farm_asset', $values);
    farm_asset_save($group_asset);

    // Save an association with the old term ID.
    $sandbox['groups'][$tid] = $group_asset->id;
  }

  // The overall update is not finished.
  $sandbox['#finished'] = 0.25;

  // Once we've processed all of the groups, we are ready for stage 3.
  if ($sandbox['stage2_progress'] >= $sandbox['stage2_max']) {
    $sandbox['stage'] = 3;
  }
}