Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/customization/user_provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,17 @@ class UserModel extends ShieldUserModel
}
}
```

## Creating a Custom User Entity

Starting from v1.2.0, `UserModel` in Shield has the `createNewUser()` method to
create a new User Entity.

```php
$user = $userModel->createNewUser($data);
```

It takes an optional user data array as the first argument, and passes it to the
constructor of the `$returnType` class.

If your custom User entity cannot be instantiated in this way, override this method.
9 changes: 6 additions & 3 deletions src/Controllers/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ public function registerAction(): RedirectResponse

// Save the user
$allowedPostFields = array_keys($rules);
$user = $this->getUserEntity();
$user->fill($this->request->getPost($allowedPostFields));
$user = $users->createNewUser($this->request->getPost($allowedPostFields));

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

/**
* Returns the Entity class that should be used
*
* @deprecated 1.2.0 No longer used.
*/
protected function getUserEntity(): User
{
return new User();
$userProvider = $this->getUserProvider();

return $userProvider->createNewUser();
}

/**
Expand Down
10 changes: 10 additions & 0 deletions src/Models/UserModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,14 @@ private function checkReturnType(): void
throw new LogicException('Return type must be a subclass of ' . User::class);
}
}

/**
* Returns a new User Entity.
*
* @param array<string, array<array-key, mixed>|bool|float|int|object|string|null> $data (Optional) user data
*/
public function createNewUser(array $data = []): User
{
return new $this->returnType($data);
}
}