You are here

protected function UserDevelGenerate::generateElements in Devel 4.x

Same name and namespace in other branches
  1. 8.3 devel_generate/src/Plugin/DevelGenerate/UserDevelGenerate.php \Drupal\devel_generate\Plugin\DevelGenerate\UserDevelGenerate::generateElements()
  2. 8 devel_generate/src/Plugin/DevelGenerate/UserDevelGenerate.php \Drupal\devel_generate\Plugin\DevelGenerate\UserDevelGenerate::generateElements()
  3. 8.2 devel_generate/src/Plugin/DevelGenerate/UserDevelGenerate.php \Drupal\devel_generate\Plugin\DevelGenerate\UserDevelGenerate::generateElements()

Business logic relating with each DevelGenerate plugin.

Parameters

array $values: The input values from the settings form.

Overrides DevelGenerateBase::generateElements

File

devel_generate/src/Plugin/DevelGenerate/UserDevelGenerate.php, line 143

Class

UserDevelGenerate
Provides a UserDevelGenerate plugin.

Namespace

Drupal\devel_generate\Plugin\DevelGenerate

Code

protected function generateElements(array $values) {
  $num = $values['num'];
  $kill = $values['kill'];
  $pass = $values['pass'];
  $age = $values['time_range'];
  $roles = array_filter($values['roles']);
  if ($kill) {
    $uids = $this->userStorage
      ->getQuery()
      ->condition('uid', 1, '>')
      ->execute();
    $users = $this->userStorage
      ->loadMultiple($uids);
    $this->userStorage
      ->delete($users);
    $this
      ->setMessage($this
      ->formatPlural(count($uids), '1 user deleted', '@count users deleted.'));
  }
  if ($num > 0) {
    $names = [];
    while (count($names) < $num) {
      $name = $this
        ->getRandom()
        ->word(mt_rand(6, 12));
      $names[$name] = '';
    }
    if (empty($roles)) {
      $roles = [
        AccountInterface::AUTHENTICATED_ROLE,
      ];
    }
    foreach ($names as $name => $value) {
      $account = $this->userStorage
        ->create([
        'uid' => NULL,
        'name' => $name,
        'pass' => $pass,
        'mail' => $name . '@example.com',
        'status' => 1,
        'created' => $this->time
          ->getRequestTime() - mt_rand(0, $age),
        'roles' => array_values($roles),
        // A flag to let hook_user_* know that this is a generated user.
        'devel_generate' => TRUE,
      ]);

      // Populate all fields with sample values.
      $this
        ->populateFields($account);
      $account
        ->save();
    }
  }
  $this
    ->setMessage($this
    ->t('@num_users created.', [
    '@num_users' => $this
      ->formatPlural($num, '1 user', '@count users'),
  ]));
}