add json user repository

This commit is contained in:
Yisroel Baum 2026-04-24 10:24:57 +03:00
parent 895bfb01da
commit 3595bcbf11
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -0,0 +1,84 @@
<?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,
];
$this->writeUsers($users);
return new User(
id: $id,
email: $dto->email,
);
}
public function find(int $id): ?User
{
$users = $this->readUsers();
foreach ($users as $data) {
if ($data['id'] === $id) {
return new User(
id: $data['id'],
email: new EmailAddress($data['email']),
);
}
}
return null;
}
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;
}
}