Skip to content

Commit 2601a59

Browse files
authored
Merge pull request #1196 from kenjis/add-UserModel-createNewUser
feat: add ``UserModel::createNewUser()`` and `RegisterController` uses it
2 parents dca828a + 9bf9e7d commit 2601a59

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

docs/customization/user_provider.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,17 @@ class UserModel extends ShieldUserModel
5454
}
5555
}
5656
```
57+
58+
## Creating a Custom User Entity
59+
60+
Starting from v1.2.0, `UserModel` in Shield has the `createNewUser()` method to
61+
create a new User Entity.
62+
63+
```php
64+
$user = $userModel->createNewUser($data);
65+
```
66+
67+
It takes an optional user data array as the first argument, and passes it to the
68+
constructor of the `$returnType` class.
69+
70+
If your custom User entity cannot be instantiated in this way, override this method.

src/Controllers/RegisterController.php

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,7 @@ public function registerAction(): RedirectResponse
103103

104104
// Save the user
105105
$allowedPostFields = array_keys($rules);
106-
$user = $this->getUserEntity();
107-
$user->fill($this->request->getPost($allowedPostFields));
106+
$user = $users->createNewUser($this->request->getPost($allowedPostFields));
108107

109108
// Workaround for email only registration/login
110109
if ($user->username === null) {
@@ -160,10 +159,14 @@ protected function getUserProvider(): UserModel
160159

161160
/**
162161
* Returns the Entity class that should be used
162+
*
163+
* @deprecated 1.2.0 No longer used.
163164
*/
164165
protected function getUserEntity(): User
165166
{
166-
return new User();
167+
$userProvider = $this->getUserProvider();
168+
169+
return $userProvider->createNewUser();
167170
}
168171

169172
/**

src/Models/UserModel.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,4 +397,14 @@ private function checkReturnType(): void
397397
throw new LogicException('Return type must be a subclass of ' . User::class);
398398
}
399399
}
400+
401+
/**
402+
* Returns a new User Entity.
403+
*
404+
* @param array<string, array<array-key, mixed>|bool|float|int|object|string|null> $data (Optional) user data
405+
*/
406+
public function createNewUser(array $data = []): User
407+
{
408+
return new $this->returnType($data);
409+
}
400410
}

0 commit comments

Comments
 (0)