/core/modules/simpletest/src/UserCreationTrait.php

https://gitlab.com/reasonat/test8 · PHP · 214 lines · 107 code · 19 blank · 88 comment · 16 complexity · 176d24562614b9b7eb9ef5961688c909 MD5 · raw file

  1. <?php
  2. namespace Drupal\simpletest;
  3. use Drupal\Component\Utility\SafeMarkup;
  4. use Drupal\Core\Session\AccountInterface;
  5. use Drupal\user\Entity\Role;
  6. use Drupal\user\Entity\User;
  7. use Drupal\user\RoleInterface;
  8. /**
  9. * Provides methods to create additional test users and switch the currently
  10. * logged in one.
  11. *
  12. * This trait is meant to be used only by test classes extending
  13. * \Drupal\simpletest\TestBase.
  14. */
  15. trait UserCreationTrait {
  16. /**
  17. * Switch the current logged in user.
  18. *
  19. * @param \Drupal\Core\Session\AccountInterface $account
  20. * The user account object.
  21. */
  22. protected function setCurrentUser(AccountInterface $account) {
  23. \Drupal::currentUser()->setAccount($account);
  24. }
  25. /**
  26. * Create a user with a given set of permissions.
  27. *
  28. * @param array $permissions
  29. * Array of permission names to assign to user. Note that the user always
  30. * has the default permissions derived from the "authenticated users" role.
  31. * @param string $name
  32. * The user name.
  33. * @param bool $admin
  34. * (optional) Whether the user should be an administrator
  35. * with all the available permissions.
  36. *
  37. * @return \Drupal\user\Entity\User|false
  38. * A fully loaded user object with pass_raw property, or FALSE if account
  39. * creation fails.
  40. */
  41. protected function createUser(array $permissions = array(), $name = NULL, $admin = FALSE) {
  42. // Create a role with the given permission set, if any.
  43. $rid = FALSE;
  44. if ($permissions) {
  45. $rid = $this->createRole($permissions);
  46. if (!$rid) {
  47. return FALSE;
  48. }
  49. }
  50. // Create a user assigned to that role.
  51. $edit = array();
  52. $edit['name'] = !empty($name) ? $name : $this->randomMachineName();
  53. $edit['mail'] = $edit['name'] . '@example.com';
  54. $edit['pass'] = user_password();
  55. $edit['status'] = 1;
  56. if ($rid) {
  57. $edit['roles'] = array($rid);
  58. }
  59. if ($admin) {
  60. $edit['roles'][] = $this->createAdminRole();
  61. }
  62. $account = User::create($edit);
  63. $account->save();
  64. $this->assertTrue($account->id(), SafeMarkup::format('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), 'User login');
  65. if (!$account->id()) {
  66. return FALSE;
  67. }
  68. // Add the raw password so that we can log in as this user.
  69. $account->pass_raw = $edit['pass'];
  70. // Support BrowserTestBase as well.
  71. $account->passRaw = $account->pass_raw;
  72. return $account;
  73. }
  74. /**
  75. * Creates an administrative role.
  76. *
  77. * @param string $rid
  78. * (optional) The role ID (machine name). Defaults to a random name.
  79. * @param string $name
  80. * (optional) The label for the role. Defaults to a random string.
  81. * @param int $weight
  82. * (optional) The weight for the role. Defaults NULL so that entity_create()
  83. * sets the weight to maximum + 1.
  84. *
  85. * @return string
  86. * Role ID of newly created role, or FALSE if role creation failed.
  87. */
  88. protected function createAdminRole($rid = NULL, $name = NULL, $weight = NULL) {
  89. $rid = $this->createRole([], $rid, $name, $weight);
  90. if ($rid) {
  91. /** @var \Drupal\user\RoleInterface $role */
  92. $role = Role::load($rid);
  93. $role->setIsAdmin(TRUE);
  94. $role->save();
  95. }
  96. return $rid;
  97. }
  98. /**
  99. * Creates a role with specified permissions.
  100. *
  101. * @param array $permissions
  102. * Array of permission names to assign to role.
  103. * @param string $rid
  104. * (optional) The role ID (machine name). Defaults to a random name.
  105. * @param string $name
  106. * (optional) The label for the role. Defaults to a random string.
  107. * @param int $weight
  108. * (optional) The weight for the role. Defaults NULL so that entity_create()
  109. * sets the weight to maximum + 1.
  110. *
  111. * @return string
  112. * Role ID of newly created role, or FALSE if role creation failed.
  113. */
  114. protected function createRole(array $permissions, $rid = NULL, $name = NULL, $weight = NULL) {
  115. // Generate a random, lowercase machine name if none was passed.
  116. if (!isset($rid)) {
  117. $rid = strtolower($this->randomMachineName(8));
  118. }
  119. // Generate a random label.
  120. if (!isset($name)) {
  121. // In the role UI role names are trimmed and random string can start or
  122. // end with a space.
  123. $name = trim($this->randomString(8));
  124. }
  125. // Check the all the permissions strings are valid.
  126. if (!$this->checkPermissions($permissions)) {
  127. return FALSE;
  128. }
  129. // Create new role.
  130. $role = Role::create(array(
  131. 'id' => $rid,
  132. 'label' => $name,
  133. ));
  134. if (isset($weight)) {
  135. $role->set('weight', $weight);
  136. }
  137. $result = $role->save();
  138. $this->assertIdentical($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', array(
  139. '@name' => var_export($role->label(), TRUE),
  140. '@rid' => var_export($role->id(), TRUE),
  141. )), 'Role');
  142. if ($result === SAVED_NEW) {
  143. // Grant the specified permissions to the role, if any.
  144. if (!empty($permissions)) {
  145. $this->grantPermissions($role, $permissions);
  146. $assigned_permissions = Role::load($role->id())->getPermissions();
  147. $missing_permissions = array_diff($permissions, $assigned_permissions);
  148. if (!$missing_permissions) {
  149. $this->pass(SafeMarkup::format('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), 'Role');
  150. }
  151. else {
  152. $this->fail(SafeMarkup::format('Failed to create permissions: @perms', array('@perms' => implode(', ', $missing_permissions))), 'Role');
  153. }
  154. }
  155. return $role->id();
  156. }
  157. else {
  158. return FALSE;
  159. }
  160. }
  161. /**
  162. * Checks whether a given list of permission names is valid.
  163. *
  164. * @param array $permissions
  165. * The permission names to check.
  166. *
  167. * @return bool
  168. * TRUE if the permissions are valid, FALSE otherwise.
  169. */
  170. protected function checkPermissions(array $permissions) {
  171. $available = array_keys(\Drupal::service('user.permissions')->getPermissions());
  172. $valid = TRUE;
  173. foreach ($permissions as $permission) {
  174. if (!in_array($permission, $available)) {
  175. $this->fail(SafeMarkup::format('Invalid permission %permission.', array('%permission' => $permission)), 'Role');
  176. $valid = FALSE;
  177. }
  178. }
  179. return $valid;
  180. }
  181. /**
  182. * Grant permissions to a user role.
  183. *
  184. * @param \Drupal\user\RoleInterface $role
  185. * The ID of a user role to alter.
  186. * @param array $permissions
  187. * (optional) A list of permission names to grant.
  188. */
  189. protected function grantPermissions(RoleInterface $role, array $permissions) {
  190. foreach ($permissions as $permission) {
  191. $role->grantPermission($permission);
  192. }
  193. $role->trustData()->save();
  194. }
  195. }