Esempio n. 1
0
 /**
  * @param array $fields
  *   Additional data for user account.
  *
  * @throws \Exception
  *
  * @return \stdClass
  */
 public function createTestUser(array $fields = [])
 {
     $random = $this->getRandom();
     $username = $random->name(8);
     $user = ['name' => $username, 'pass' => $random->name(16), 'mail' => "{$username}@example.com", 'roles' => [DRUPAL_AUTHENTICATED_RID => 'authenticated user']];
     $user = (object) $user;
     if (!empty($fields)) {
         $entity = new EntityDrupalWrapper('user');
         $required = $entity->getRequiredFields();
         // Fill fields. Field can be found by name or label.
         foreach ($fields as $field_name => $value) {
             $field_info = $entity->getFieldInfo($field_name);
             if (!empty($field_info)) {
                 $field_name = $field_info['field_name'];
             }
             $user->{$field_name} = $value;
             // Remove field from $required if it was there and filled.
             unset($required[$field_name]);
         }
         // Throw an exception when one of required fields was not filled.
         if (!empty($required)) {
             throw new \Exception(sprintf('The following fields "%s" are required and has not filled.', implode('", "', $required)));
         }
     }
     if (isset($user->name)) {
         $existing_user = user_load_by_name($user->name);
         if (!empty($existing_user)) {
             user_delete($existing_user->uid);
         }
     }
     // $this->user always exist but when no user created it has "false" as a value.
     // Variable stored to another because RawDrupalContext::userCreate() will modify
     // it and this will affect for future actions.
     if (!empty($this->user)) {
         $tmp = $this->user;
     }
     $this->userCreate($user);
     if (isset($tmp)) {
         $this->user = $tmp;
     }
     return $user;
 }