Goal-Calibration/app/User/JsonUserRepository.php

84 lines
1.7 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,
];
$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;
}
}