first commit

This commit is contained in:
julien
2026-03-16 01:47:07 +01:00
commit 8f7e61bda0
185 changed files with 27731 additions and 0 deletions

89
src/User/UserService.php Normal file
View 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;
}
}