You are here

public static function UserImportController::userImport in Simple Node Importer 8

Initiate Batch process for User Import.

1 string reference to 'UserImportController::userImport'
simple_node_importer.routing.yml in ./simple_node_importer.routing.yml
simple_node_importer.routing.yml

File

src/Controller/UserImportController.php, line 19

Class

UserImportController
Default controller for the simple_node_importer module.

Namespace

Drupal\simple_node_importer\Controller

Code

public static function userImport($records, &$context) {
  $entity_type = 'user';
  foreach ($records as $record) {

    // Get user details if exists otherwse create.
    $batch_result['result'] = [];
    $user_data = [];
    if (empty($record['name'])) {
      $batch_result['result'] = $record;
    }
    $user = \Drupal::service('snp.get_services')
      ->getUserByUsername($record['name']);
    if (!empty($record['mail'])) {
      $flag = \Drupal::service('email.validator')
        ->isValid($record['mail']);
      $usermail_exist = \Drupal::service('snp.get_services')
        ->getUserByEmail($record['mail'], 'content_validate');
      if ($usermail_exist != NULL || $flag == FALSE) {
        $batch_result['result'] = $record;
      }
    }
    if ($user) {
      $batch_result['result'] = $record;
    }
    $field_names = array_keys($record);
    $user_data = [
      'type' => 'user',
      'mail' => !empty($record['mail']) ? $record['mail'] : '',
      'name' => $record['name'],
      'status' => $record['status'] == 1 || $record['status'] == TRUE ? TRUE : FALSE,
      'roles' => !empty($record['roles']) ? $record['roles'] : 'authenticated',
    ];
    if (empty($batch_result['result'])) {
      $batch_result = \Drupal::service('snp.get_services')
        ->checkFieldWidget($field_names, $record, $user_data, $entity_type);
    }
    if (!empty($batch_result['result'])) {
      if (!isset($context['results']['failed'])) {
        $context['results']['failed'] = 0;
      }
      $context['results']['failed']++;
      $batch_result['result']['sni_id'] = $context['results']['failed'];
      $context['results']['sni_nid'] = $record['nid'];
      $context['results']['data'][] = serialize($batch_result['result']);
    }
    else {
      $user_data = $batch_result;
      $user_account = User::create($user_data);
      $user_account
        ->save();
      $id = $user_account
        ->id();
      if ($id) {
        if (!isset($context['results']['created'])) {
          $context['results']['created'] = 0;
        }
        $context['results']['created']++;
      }
      else {
        $context['results']['failed']++;
        $batch_result['result']['sni_id'] = $context['results']['failed'];
        $context['results']['sni_nid'] = $record['nid'];
        $context['results']['data'] = $batch_result['result'];
      }
    }
  }
}