comparison core/modules/user/tests/src/Traits/UserCreationTrait.php @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents a9cd425dd02b
children
comparison
equal deleted inserted replaced
4:a9cd425dd02b 5:12f9dff5fda9
1 <?php 1 <?php
2 2
3 namespace Drupal\Tests\user\Traits; 3 namespace Drupal\Tests\user\Traits;
4 4
5 use Drupal\Component\Render\FormattableMarkup; 5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Database\DatabaseExceptionWrapper;
7 use Drupal\Core\Database\SchemaObjectExistsException;
8 use Drupal\Core\Entity\EntityStorageException;
6 use Drupal\Core\Session\AccountInterface; 9 use Drupal\Core\Session\AccountInterface;
10 use Drupal\KernelTests\KernelTestBase;
7 use Drupal\user\Entity\Role; 11 use Drupal\user\Entity\Role;
8 use Drupal\user\Entity\User; 12 use Drupal\user\Entity\User;
9 use Drupal\user\RoleInterface; 13 use Drupal\user\RoleInterface;
10 14
11 /** 15 /**
15 * This trait is meant to be used only by test classes. 19 * This trait is meant to be used only by test classes.
16 */ 20 */
17 trait UserCreationTrait { 21 trait UserCreationTrait {
18 22
19 /** 23 /**
24 * Creates a random user account and sets it as current user.
25 *
26 * Unless explicitly specified by setting the user ID to 1, a regular user
27 * account will be created and set as current, after creating user account 1.
28 * Additionally, this will ensure that at least the anonymous user account
29 * exists regardless of the specified user ID.
30 *
31 * @param array $values
32 * (optional) An array of initial user field values.
33 * @param array $permissions
34 * (optional) Array of permission names to assign to user. Note that the
35 * user always has the default permissions derived from the "authenticated
36 * users" role.
37 * @param bool $admin
38 * (optional) Whether the user should be an administrator with all the
39 * available permissions.
40 *
41 * @return \Drupal\user\UserInterface
42 * A user account object.
43 *
44 * @throws \LogicException
45 * If attempting to assign additional roles to the anonymous user account.
46 * @throws \Drupal\Core\Entity\EntityStorageException
47 * If the user could not be saved.
48 */
49 protected function setUpCurrentUser(array $values = [], array $permissions = [], $admin = FALSE) {
50 $values += [
51 'name' => $this->randomMachineName(),
52 ];
53
54 // In many cases the anonymous user account is fine for testing purposes,
55 // however, if we need to create a user with a non-empty ID, we need also
56 // the "sequences" table.
57 if (!\Drupal::moduleHandler()->moduleExists('system')) {
58 $values['uid'] = 0;
59 }
60 if ($this instanceof KernelTestBase && (!isset($values['uid']) || $values['uid'])) {
61 try {
62 $this->installSchema('system', ['sequences']);
63 }
64 catch (SchemaObjectExistsException $e) {
65 }
66 }
67
68 // Creating an administrator or assigning custom permissions would result in
69 // creating and assigning a new role to the user. This is not possible with
70 // the anonymous user account.
71 if (($admin || $permissions) && isset($values['uid']) && is_numeric($values['uid']) && $values['uid'] == 0) {
72 throw new \LogicException('The anonymous user account cannot have additional roles.');
73 }
74
75 $original_permissions = $permissions;
76 $original_admin = $admin;
77 $original_values = $values;
78 $autocreate_user_1 = !isset($values['uid']) || $values['uid'] > 1;
79
80 // No need to create user account 1 if it already exists.
81 try {
82 $autocreate_user_1 = $autocreate_user_1 && !User::load(1);
83 }
84 catch (DatabaseExceptionWrapper $e) {
85 // Missing schema, it will be created later on.
86 }
87
88 // Save the user entity object and created its schema if needed.
89 try {
90 if ($autocreate_user_1) {
91 $permissions = [];
92 $admin = FALSE;
93 $values = [];
94 }
95 $user = $this->createUser($permissions, NULL, $admin, $values);
96 }
97 catch (EntityStorageException $e) {
98 if ($this instanceof KernelTestBase) {
99 $this->installEntitySchema('user');
100 $user = $this->createUser($permissions, NULL, $admin, $values);
101 }
102 else {
103 throw $e;
104 }
105 }
106
107 // Ensure the anonymous user account exists.
108 if (!User::load(0)) {
109 $values = [
110 'uid' => 0,
111 'status' => 0,
112 'name' => '',
113 ];
114 User::create($values)->save();
115 }
116
117 // If we automatically created user account 1, we need to create a regular
118 // user account before setting up the current user service to avoid
119 // potential false positives caused by access control bypass.
120 if ($autocreate_user_1) {
121 $user = $this->createUser($original_permissions, NULL, $original_admin, $original_values);
122 }
123
124 $this->setCurrentUser($user);
125
126 return $user;
127 }
128
129 /**
20 * Switch the current logged in user. 130 * Switch the current logged in user.
21 * 131 *
22 * @param \Drupal\Core\Session\AccountInterface $account 132 * @param \Drupal\Core\Session\AccountInterface $account
23 * The user account object. 133 * The user account object.
24 */ 134 */
35 * @param string $name 145 * @param string $name
36 * The user name. 146 * The user name.
37 * @param bool $admin 147 * @param bool $admin
38 * (optional) Whether the user should be an administrator 148 * (optional) Whether the user should be an administrator
39 * with all the available permissions. 149 * with all the available permissions.
150 * @param array $values
151 * (optional) An array of initial user field values.
40 * 152 *
41 * @return \Drupal\user\Entity\User|false 153 * @return \Drupal\user\Entity\User|false
42 * A fully loaded user object with pass_raw property, or FALSE if account 154 * A fully loaded user object with pass_raw property, or FALSE if account
43 * creation fails. 155 * creation fails.
44 */ 156 *
45 protected function createUser(array $permissions = [], $name = NULL, $admin = FALSE) { 157 * @throws \Drupal\Core\Entity\EntityStorageException
158 * If the user creation fails.
159 */
160 protected function createUser(array $permissions = [], $name = NULL, $admin = FALSE, array $values = []) {
46 // Create a role with the given permission set, if any. 161 // Create a role with the given permission set, if any.
47 $rid = FALSE; 162 $rid = FALSE;
48 if ($permissions) { 163 if ($permissions) {
49 $rid = $this->createRole($permissions); 164 $rid = $this->createRole($permissions);
50 if (!$rid) { 165 if (!$rid) {
51 return FALSE; 166 return FALSE;
52 } 167 }
53 } 168 }
54 169
55 // Create a user assigned to that role. 170 // Create a user assigned to that role.
56 $edit = []; 171 $edit = $values;
57 $edit['name'] = !empty($name) ? $name : $this->randomMachineName(); 172 if ($name) {
58 $edit['mail'] = $edit['name'] . '@example.com'; 173 $edit['name'] = $name;
59 $edit['pass'] = user_password(); 174 }
60 $edit['status'] = 1; 175 elseif (!isset($values['name'])) {
176 $edit['name'] = $this->randomMachineName();
177 }
178 $edit += [
179 'mail' => $edit['name'] . '@example.com',
180 'pass' => user_password(),
181 'status' => 1,
182 ];
61 if ($rid) { 183 if ($rid) {
62 $edit['roles'] = [$rid]; 184 $edit['roles'] = [$rid];
63 } 185 }
64 186
65 if ($admin) { 187 if ($admin) {
67 } 189 }
68 190
69 $account = User::create($edit); 191 $account = User::create($edit);
70 $account->save(); 192 $account->save();
71 193
72 $this->assertTrue($account->id(), new FormattableMarkup('User created with name %name and pass %pass', ['%name' => $edit['name'], '%pass' => $edit['pass']]), 'User login'); 194 $valid_user = $account->id() !== NULL;
73 if (!$account->id()) { 195 $this->assertTrue($valid_user, new FormattableMarkup('User created with name %name and pass %pass', ['%name' => $edit['name'], '%pass' => $edit['pass']]), 'User login');
196 if (!$valid_user) {
74 return FALSE; 197 return FALSE;
75 } 198 }
76 199
77 // Add the raw password so that we can log in as this user. 200 // Add the raw password so that we can log in as this user.
78 $account->pass_raw = $edit['pass']; 201 $account->pass_raw = $edit['pass'];