You are here

protected function BulkUserImport::handleFileData in Bulk User Registration 8

To import data as users.

Parameters

\Symfony\Component\HttpFoundation\FileBag $filedata: Field data.

string $defaultRole: The default role.

1 call to BulkUserImport::handleFileData()
BulkUserImport::submitForm in src/Form/BulkUserImport.php
Form submission handler.

File

src/Form/BulkUserImport.php, line 129

Class

BulkUserImport
Bulk user import form.

Namespace

Drupal\bulk_user_registration\Form

Code

protected function handleFileData(FileBag $filedata, $defaultRole) {

  /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile */
  $uploadedFiles = $filedata
    ->get('files');
  $location = $uploadedFiles['file_upload']
    ->getRealPath();
  if (($handle = fopen($location, 'r')) === FALSE) {
    return;
  }

  // Read the csv data.
  $headerData = [];
  $csvData = [];
  while (($data = fgetcsv($handle)) !== FALSE) {
    if (empty($headerData)) {
      $headerData = $data;
    }
    else {
      $csvData[] = $data;
    }
  }
  fclose($handle);

  // Only standard and extra fields are allowed as csv columns. Unknown
  // fields will be ignored.
  $fieldNames = $this->bulkUserRegistration
    ->getFieldNames();
  $columnsToIgnore = [];
  foreach ($headerData as $column => $header) {
    if (!isset($fieldNames[$header])) {
      $columnsToIgnore[] = $column;
    }
  }

  // Collect the user data in a structured array. Where keys are the
  // names of the appropriate header column.
  $userData = [];
  foreach ($csvData as $csvRow) {
    $row_data = [];
    foreach ($csvRow as $column => $value) {
      if (in_array($column, $columnsToIgnore)) {
        continue;
      }
      $row_data[$headerData[$column]] = trim($value);
    }
    $userData[] = $row_data;
  }
  $userData = array_filter($userData);
  $this
    ->batchProcessUserInfo($userData, $defaultRole);
}