Goal-Calibration/app/User/JsonUserRepository.php

108 lines
2.3 KiB
PHP

<?php
namespace App\User;
use App\User\UseCases\CreateUserDto;
use App\ValueObjects\EmailAddress;
class JsonUserRepository implements UserRepository
{
private string $filePath;
public function __construct()
{
$this->filePath = __DIR__ . '/../../data/users.json';
}
public function create(CreateUserDto $dto): User
{
$users = $this->readUsers();
$id = $this->getNextId($users);
$users[] = [
'id' => $id,
'email' => (string) $dto->email,
'passwordHash' => $dto->passwordHash,
'isAdmin' => $dto->isAdmin,
];
$this->writeUsers($users);
return new User(
id: $id,
email: $dto->email,
passwordHash: $dto->passwordHash,
isAdmin: $dto->isAdmin,
);
}
public function find(int $id): ?User
{
$users = $this->readUsers();
foreach ($users as $data) {
if ($data['id'] === $id) {
return $this->hydrate($data);
}
}
return null;
}
public function findByEmail(EmailAddress $email): ?User
{
$users = $this->readUsers();
foreach ($users as $data) {
if ($data['email'] === (string) $email) {
return $this->hydrate($data);
}
}
return null;
}
private function hydrate(array $data): User
{
return new User(
id: $data['id'],
email: new EmailAddress($data['email']),
passwordHash: $data['passwordHash'] ?? '',
isAdmin: $data['isAdmin'] ?? false,
);
}
private function readUsers(): array
{
if (!file_exists($this->filePath)) {
return [];
}
$content = file_get_contents($this->filePath);
return json_decode($content, true) ?? [];
}
private function writeUsers(array $users): void
{
file_put_contents(
$this->filePath,
json_encode($users, JSON_PRETTY_PRINT)
);
}
private function getNextId(array $users): int
{
if (empty($users)) {
return 0;
}
$maxId = -1;
foreach ($users as $user) {
if ($user['id'] > $maxId) {
$maxId = $user['id'];
}
}
return $maxId + 1;
}
}