Skip to content

Commit

Permalink
Merge pull request #1196 from kenjis/add-UserModel-createNewUser
Browse files Browse the repository at this point in the history
feat: add ``UserModel::createNewUser()``  and `RegisterController` uses it
  • Loading branch information
datamweb authored Feb 6, 2025
2 parents dca828a + 9bf9e7d commit 2601a59
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
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 @@ -397,4 +397,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);
}
}

0 comments on commit 2601a59

Please sign in to comment.