Version 1
[yaffs-website] / web / modules / contrib / devel / devel_generate / src / Plugin / DevelGenerate / UserDevelGenerate.php
1 <?php
2
3 namespace Drupal\devel_generate\Plugin\DevelGenerate;
4
5 use Drupal\Core\Datetime\DateFormatterInterface;
6 use Drupal\Core\Entity\EntityStorageInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
9 use Drupal\devel_generate\DevelGenerateBase;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
11
12 /**
13  * Provides a UserDevelGenerate plugin.
14  *
15  * @DevelGenerate(
16  *   id = "user",
17  *   label = @Translation("users"),
18  *   description = @Translation("Generate a given number of users. Optionally delete current users."),
19  *   url = "user",
20  *   permission = "administer devel_generate",
21  *   settings = {
22  *     "num" = 50,
23  *     "kill" = FALSE,
24  *     "pass" = ""
25  *   }
26  * )
27  */
28 class UserDevelGenerate extends DevelGenerateBase implements ContainerFactoryPluginInterface {
29
30   /**
31    * The user storage.
32    *
33    * @var \Drupal\Core\Entity\EntityStorageInterface
34    */
35   protected $userStorage;
36
37   /**
38    * The date formatter service.
39    *
40    * @var \Drupal\Core\Datetime\DateFormatterInterface
41    */
42   protected $dateFormatter;
43
44   /**
45    * Constructs a new UserDevelGenerate object.
46    *
47    * @param array $configuration
48    *   A configuration array containing information about the plugin instance.
49    * @param string $plugin_id
50    *   The plugin_id for the plugin instance.
51    * @param mixed $plugin_definition
52    *   The plugin implementation definition.
53    * @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage
54    *   The user storage.
55    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
56    *   The date formatter service.
57    */
58   public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityStorageInterface $entity_storage, DateFormatterInterface $date_formatter) {
59     parent::__construct($configuration, $plugin_id, $plugin_definition);
60
61     $this->userStorage = $entity_storage;
62     $this->dateFormatter = $date_formatter;
63   }
64
65   /**
66    * {@inheritdoc}
67    */
68   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
69     return new static(
70       $configuration, $plugin_id, $plugin_definition,
71       $container->get('entity.manager')->getStorage('user'),
72       $container->get('date.formatter')
73     );
74   }
75
76   /**
77    * {@inheritdoc}
78    */
79   public function settingsForm(array $form, FormStateInterface $form_state) {
80     $form['num'] = array(
81       '#type' => 'number',
82       '#title' => $this->t('How many users would you like to generate?'),
83       '#default_value' => $this->getSetting('num'),
84       '#required' => TRUE,
85       '#min' => 0,
86     );
87
88     $form['kill'] = array(
89       '#type' => 'checkbox',
90       '#title' => $this->t('Delete all users (except user id 1) before generating new users.'),
91       '#default_value' => $this->getSetting('kill'),
92     );
93
94     $options = user_role_names(TRUE);
95     unset($options[DRUPAL_AUTHENTICATED_RID]);
96     $form['roles'] = array(
97       '#type' => 'checkboxes',
98       '#title' => $this->t('Which roles should the users receive?'),
99       '#description' => $this->t('Users always receive the <em>authenticated user</em> role.'),
100       '#options' => $options,
101     );
102
103     $form['pass'] = array(
104       '#type' => 'textfield',
105       '#title' => $this->t('Password to be set'),
106       '#default_value' => $this->getSetting('pass'),
107       '#size' => 32,
108       '#description' => $this->t('Leave this field empty if you do not need to set a password'),
109     );
110
111     $options = array(1 => $this->t('Now'));
112     foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
113       $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
114     }
115     $form['time_range'] = array(
116       '#type' => 'select',
117       '#title' => $this->t('How old should user accounts be?'),
118       '#description' => $this->t('User ages will be distributed randomly from the current time, back to the selected time.'),
119       '#options' => $options,
120       '#default_value' => 604800,
121     );
122
123     return $form;
124   }
125
126   /**
127    * {@inheritdoc}
128    */
129   protected function generateElements(array $values) {
130     $num = $values['num'];
131     $kill = $values['kill'];
132     $pass = $values['pass'];
133     $age = $values['time_range'];
134     $roles = array_filter($values['roles']);
135
136     if ($kill) {
137       $uids = $this->userStorage->getQuery()
138         ->condition('uid', 1, '>')
139         ->execute();
140       $users = $this->userStorage->loadMultiple($uids);
141       $this->userStorage->delete($users);
142
143       $this->setMessage($this->formatPlural(count($uids), '1 user deleted', '@count users deleted.'));
144     }
145
146     if ($num > 0) {
147       $names = array();
148       while (count($names) < $num) {
149         $name = $this->getRandom()->word(mt_rand(6, 12));
150         $names[$name] = '';
151       }
152
153       if (empty($roles)) {
154         $roles = array(DRUPAL_AUTHENTICATED_RID);
155       }
156       foreach ($names as $name => $value) {
157         $account = $this->userStorage->create(array(
158           'uid' => NULL,
159           'name' => $name,
160           'pass' => $pass,
161           'mail' => $name . '@example.com',
162           'status' => 1,
163           'created' => REQUEST_TIME - mt_rand(0, $age),
164           'roles' => array_values($roles),
165           // A flag to let hook_user_* know that this is a generated user.
166           'devel_generate' => TRUE,
167         ));
168
169         // Populate all fields with sample values.
170         $this->populateFields($account);
171         $account->save();
172       }
173     }
174     $this->setMessage($this->t('@num_users created.', array('@num_users' => $this->formatPlural($num, '1 user', '@count users'))));
175   }
176
177   /**
178    * {@inheritdoc}
179    */
180   public function validateDrushParams($args) {
181     $values = array(
182       'num' => array_shift($args),
183       'roles' => drush_get_option('roles') ? explode(',', drush_get_option('roles')) : array(),
184       'kill' => drush_get_option('kill'),
185       'pass' => drush_get_option('pass', NULL),
186       'time_range' => 0,
187     );
188     return $values;
189   }
190
191 }