You are here

function _farm_livestock_update_7005_stage3 in farmOS 7

Update 7005 stage 3: Assign animals to new group assets.

See also

farm_livestock_update_7005().

1 call to _farm_livestock_update_7005_stage3()
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 243
Farm livestock install file.

Code

function _farm_livestock_update_7005_stage3(&$sandbox) {

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

  // Prepare to process this stage in batches.
  if (!isset($sandbox['stage3_progress'])) {
    $sandbox['stage3_progress'] = 0;
    $sandbox['stage3_max'] = db_query("SELECT COUNT(id) FROM {farm_asset} WHERE type = 'animal' ORDER BY id ASC")
      ->fetchField();
  }

  // Load the next batch of animal asset IDs.
  $limit = 25;
  $result = db_query_range("SELECT id FROM {farm_asset} WHERE type = 'animal' ORDER BY id ASC", $sandbox['stage3_progress'], $limit);
  $animal_ids = array();
  foreach ($result as $row) {
    if (!empty($row->id)) {
      $animal_ids[] = $row->id;
    }
  }

  // Iterate through the animals.
  foreach ($animal_ids as $animal_id) {

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

    // Load the animal.
    $animal = farm_asset_load($animal_id);

    // Get the IDs of the old group terms this animal is assigned to.
    $old_group_ids = array();
    if (!empty($animal->field_farm_animal_group[LANGUAGE_NONE])) {
      foreach ($animal->field_farm_animal_group[LANGUAGE_NONE] as $value) {
        if (!empty($value['tid'])) {
          $old_group_ids[] = $value['tid'];
        }
      }
    }

    // Build an array of new group IDs.
    $new_group_ids = array();
    foreach ($old_group_ids as $old_group_id) {
      if (!empty($sandbox['groups'][$old_group_id])) {
        $new_group_ids[] = $sandbox['groups'][$old_group_id];
      }
    }

    // Load the groups.
    $groups = farm_asset_load_multiple($new_group_ids);

    // If there are no groups, don't do anything (skip to the next animal).
    if (empty($groups)) {
      continue;
    }

    // Create a log assigning this animal to the new group asset(s). Use the
    // animals creation date as the date of the log.
    farm_group_membership_set($animal, $groups, $animal->created);
  }

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

  // Once we've processed all of the animals, we are ready for stage 4.
  if ($sandbox['stage3_progress'] >= $sandbox['stage3_max']) {
    $sandbox['stage'] = 4;
  }
}