You are here

public static function DataService::processBatch in Weather 8

Same name and namespace in other branches
  1. 2.0.x src/Service/DataService.php \Drupal\weather\Service\DataService::processBatch()

Batch process callback.

File

src/Service/DataService.php, line 130

Class

DataService
DataService service.

Namespace

Drupal\weather\Service

Code

public static function processBatch($items, $operation, &$context) {
  $placeStorage = \Drupal::entityTypeManager()
    ->getStorage('weather_place');

  // Use the $context['sandbox'] at your convenience to store the
  // information needed to track progression between successive calls.
  if (empty($context['sandbox'])) {
    $context['sandbox'] = [];
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($items);
  }
  $limit = 50;

  // Retrieve the next group.
  $range = array_slice($items, $context['sandbox']['progress'], $limit);
  foreach ($range as $item) {
    $id = $operation == 'add' ? $item[0] : $item;
    if ($operation == 'add') {
      $placeStorage
        ->create([
        'geoid' => $item[0],
        'latitude' => $item[1],
        'longitude' => $item[2],
        'country' => $item[3],
        'name' => $item[4],
        'link' => trim($item[5]),
        'status' => WeatherPlaceInterface::STATUS_ORIGINAL,
      ])
        ->save();
    }
    elseif ($operation == 'remove') {
      $placeStorage
        ->load($item)
        ->delete();
    }
    $context['message'] = t('@op @current out of @total weather places. @details', [
      '@op' => $operation == 'add' ? 'Imported' : 'Deleted',
      '@current' => $context['sandbox']['progress'],
      '@total' => $context['sandbox']['max'],
      '@details' => $id,
    ]);
    $context['results'][] = $id;
    $context['sandbox']['progress']++;
  }
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}