Skip to content

feat: add UserModel::createNewUser() and RegisterController uses it #1196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 6, 2025
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);
}
}
Loading