diff --git a/app/Plan/JsonPlanRepository.php b/app/Plan/JsonPlanRepository.php new file mode 100644 index 0000000..8a88838 --- /dev/null +++ b/app/Plan/JsonPlanRepository.php @@ -0,0 +1,93 @@ +filePath = __DIR__ . '/../../data/plans.json'; + } + + public function create(CreatePlanDto $dto): Plan + { + $plans = $this->readPlans(); + $id = $this->getNextId($plans); + + $plans[] = [ + 'id' => $id, + 'name' => $dto->name, + 'userId' => $dto->user->getId(), + ]; + $this->writePlans($plans); + + return new Plan( + id: $id, + name: $dto->name, + user: $dto->user, + ); + } + + public function find(int $id): ?Plan + { + $plans = $this->readPlans(); + + foreach ($plans as $data) { + if ($data['id'] === $id) { + $user = $this->userRepository->find($data['userId']); + if ($user === null) { + return null; + } + return new Plan( + id: $data['id'], + name: $data['name'], + user: $user, + ); + } + } + + return null; + } + + private function readPlans(): array + { + if (!file_exists($this->filePath)) { + return []; + } + + $content = file_get_contents($this->filePath); + + return json_decode($content, true) ?? []; + } + + private function writePlans(array $plans): void + { + file_put_contents( + $this->filePath, + json_encode($plans, JSON_PRETTY_PRINT) + ); + } + + private function getNextId(array $plans): int + { + if (empty($plans)) { + return 0; + } + + $maxId = -1; + foreach ($plans as $plan) { + if ($plan['id'] > $maxId) { + $maxId = $plan['id']; + } + } + + return $maxId + 1; + } +}