You are here

public static function MetatagImport::importCsvBatchOperation in Metatag Import Export CSV 8

Batch callback for parsing the CSV.

Parameters

array $headers: The header row of the CSV file. This must contain an 'entity_type' and 'entity_id' column.

array $filepath: The filepath to the uploaded CSV file.

array $context: The batch context.

File

src/MetatagImport.php, line 56

Class

MetatagImport
Class for batch process for metatag import.

Namespace

Drupal\metatag_import_export_csv

Code

public static function importCsvBatchOperation($headers, $filepath, &$context = []) {

  // Initial setup on the first operation.
  if (empty($context['sandbox'])) {
    $context['sandbox']['handle'] = NULL;
    $context['sandbox']['pointer_position'] = 0;
    $context['sandbox']['csv_line'] = 0;
    $context['results']['success'] = [];
    $context['results']['error'] = [];
  }
  if (!is_resource($context['sandbox']['handle'])) {
    $context['sandbox']['handle'] = fopen($filepath, 'r');
  }

  // If we've reached the end of the file, we're done.
  if (feof($context['sandbox']['handle'])) {
    $context['finished'] = 1;
    return;
  }
  if ($context['sandbox']['pointer_position'] == 0) {

    // On the first operation, discard the CSV header row.
    fgetcsv($context['sandbox']['handle']);
    $context['sandbox']['csv_line']++;
  }
  else {

    // On subsequent operations, move the pointer to where it was for the last
    // operation.
    fseek($context['sandbox']['handle'], $context['sandbox']['pointer_position']);
  }

  // Get the data, and update our stored pointer.
  $data = fgetcsv($context['sandbox']['handle']);
  $context['sandbox']['csv_line']++;
  $context['sandbox']['pointer_position'] = ftell($context['sandbox']['handle']);
  try {
    $entity = static::importCsvRow($headers, $data);
    $context['results']['success'][$entity
      ->getEntityTypeId()][] = $entity
      ->id();
  } catch (\Exception $e) {
    $context['results']['error'][] = t("Unable to import line @line of the CSV. Error was: '@message'.", [
      '@line' => $context['sandbox']['csv_line'],
      '@message' => $e
        ->getMessage(),
    ]);
  }

  // We're not finished until we reach the end of the CSV file.
  $context['finished'] = 0;
}