first commit
This commit is contained in:
89
src/User/UserService.php
Normal file
89
src/User/UserService.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\User;
|
||||
|
||||
use App\Shared\Exception\NotFoundException;
|
||||
use App\User\Exception\DuplicateEmailException;
|
||||
use App\User\Exception\DuplicateUsernameException;
|
||||
use App\User\Exception\InvalidRoleException;
|
||||
use App\User\Exception\WeakPasswordException;
|
||||
|
||||
final class UserService implements UserServiceInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserRepositoryInterface $userRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
public function findAll(): array
|
||||
{
|
||||
return $this->userRepository->findAll();
|
||||
}
|
||||
|
||||
public function findById(int $id): ?User
|
||||
{
|
||||
return $this->userRepository->findById($id);
|
||||
}
|
||||
|
||||
public function delete(int $id): void
|
||||
{
|
||||
$this->requireExistingUser($id);
|
||||
$this->userRepository->delete($id);
|
||||
}
|
||||
|
||||
public function updateRole(int $id, string $role): void
|
||||
{
|
||||
$this->assertValidRole($role);
|
||||
$this->requireExistingUser($id);
|
||||
$this->userRepository->updateRole($id, $role);
|
||||
}
|
||||
|
||||
public function createUser(string $username, string $email, string $plainPassword, string $role = User::ROLE_USER): User
|
||||
{
|
||||
$username = mb_strtolower(trim($username));
|
||||
$email = mb_strtolower(trim($email));
|
||||
$plainPassword = trim($plainPassword);
|
||||
|
||||
$this->assertValidRole($role);
|
||||
|
||||
if ($this->userRepository->findByUsername($username)) {
|
||||
throw new DuplicateUsernameException($username);
|
||||
}
|
||||
|
||||
if ($this->userRepository->findByEmail($email)) {
|
||||
throw new DuplicateEmailException($email);
|
||||
}
|
||||
|
||||
if (mb_strlen($plainPassword) < 8) {
|
||||
throw new WeakPasswordException();
|
||||
}
|
||||
|
||||
$passwordHash = password_hash($plainPassword, PASSWORD_BCRYPT, ['cost' => 12]);
|
||||
$user = new User(0, $username, $email, $passwordHash, $role);
|
||||
|
||||
$this->userRepository->create($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function assertValidRole(string $role): void
|
||||
{
|
||||
$validRoles = [User::ROLE_USER, User::ROLE_EDITOR, User::ROLE_ADMIN];
|
||||
|
||||
if (!in_array($role, $validRoles, true)) {
|
||||
throw new InvalidRoleException($role);
|
||||
}
|
||||
}
|
||||
|
||||
private function requireExistingUser(int $id): User
|
||||
{
|
||||
$user = $this->userRepository->findById($id);
|
||||
|
||||
if ($user === null) {
|
||||
throw new NotFoundException('Utilisateur', $id);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user