You are here

public static function UserCsvImportController::processUpload in User CSV import 8

Same name and namespace in other branches
  1. 2.0.x src/Controller/UserCsvImportController.php \Drupal\user_csv_import\Controller\UserCsvImportController::processUpload()
  2. 1.0.x src/Controller/UserCsvImportController.php \Drupal\user_csv_import\Controller\UserCsvImportController::processUpload()

Processes an uploaded CSV file, creating a new user for each row of values.

Parameters

\Drupal\file\Entity\File $file: The File entity to process.

array $config: An array of configuration containing fields and roles.

Return value

array An associative array of values from the filename keyed by new uid.

1 call to UserCsvImportController::processUpload()
UserCsvImportForm::submitForm in src/Form/UserCsvImportForm.php
Form submission handler.

File

src/Controller/UserCsvImportController.php, line 37

Class

UserCsvImportController
Provides methods to import CSV files and convert to users.

Namespace

Drupal\user_csv_import\Controller

Code

public static function processUpload(File $file, array $config) {

  // Open the uploaded file.
  $handle = fopen($file->destination, 'r');
  $created = [];
  $i = 0;
  $row_positions = [];

  // Iterate hover it and store the values to a new User.
  while ($row = fgetcsv($handle)) {

    // If is the first row, compare the header values with
    // selected fields if config.
    if ($i == 0) {

      // Iterate over the selected fields to find their position.
      foreach ($config['fields'] as $key => $value) {

        // Search in the file for the position of the selected fields.
        $row_positions[$key] = array_search($key, $row);
      }
    }
    else {
      if ($values = self::prepareRow($row, $config, $row_positions)) {

        // Create the user.
        if ($uid = self::createUser($values)) {
          $created[$uid] = $values;
        }
      }
    }
    $i++;
  }
  return $created;
}