diff --git a/app/User/JsonUserRepository.php b/app/User/JsonUserRepository.php new file mode 100644 index 0000000..bde8c62 --- /dev/null +++ b/app/User/JsonUserRepository.php @@ -0,0 +1,84 @@ +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; + } +}