You are here

protected function UserDevelGenerate::generateElements in Devel 8

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.2 devel_generate/src/Plugin/DevelGenerate/UserDevelGenerate.php \Drupal\devel_generate\Plugin\DevelGenerate\UserDevelGenerate::generateElements()
  3. 4.x 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 130

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 = array();
    while (count($names) < $num) {
      $name = $this
        ->getRandom()
        ->word(mt_rand(6, 12));
      $names[$name] = '';
    }
    if (empty($roles)) {
      $roles = array(
        DRUPAL_AUTHENTICATED_RID,
      );
    }
    foreach ($names as $name => $value) {
      $account = $this->userStorage
        ->create(array(
        'uid' => NULL,
        'name' => $name,
        'pass' => $pass,
        'mail' => $name . '@example.com',
        'status' => 1,
        'created' => REQUEST_TIME - 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.', array(
    '@num_users' => $this
      ->formatPlural($num, '1 user', '@count users'),
  )));
}