diff --git a/app/ScheduledNode/JsonScheduledNodeRepository.php b/app/ScheduledNode/JsonScheduledNodeRepository.php new file mode 100644 index 0000000..bee31ea --- /dev/null +++ b/app/ScheduledNode/JsonScheduledNodeRepository.php @@ -0,0 +1,67 @@ +filePath = __DIR__ . '/../../data/scheduledNodes.json'; + } + + public function create(CreateScheduledNodeDto $dto): ScheduledNode + { + $scheduledNodes = $this->readScheduledNodes(); + $id = $this->getNextId($scheduledNodes); + + $scheduledNodes[] = [ + 'id' => $id, + 'date' => $dto->date->format('Y-m-d'), + 'planId' => $dto->plan->getId(), + ]; + $this->writeScheduledNodes($scheduledNodes); + + return new ScheduledNode( + id: $id, + date: $dto->date, + plan: $dto->plan, + ); + } + + private function readScheduledNodes(): array + { + if (!file_exists($this->filePath)) { + return []; + } + + $content = file_get_contents($this->filePath); + + return json_decode($content, true) ?? []; + } + + private function writeScheduledNodes(array $scheduledNodes): void + { + file_put_contents( + $this->filePath, + json_encode($scheduledNodes, JSON_PRETTY_PRINT) + ); + } + + private function getNextId(array $scheduledNodes): int + { + if (empty($scheduledNodes)) { + return 0; + } + + $maxId = -1; + foreach ($scheduledNodes as $scheduledNode) { + if ($scheduledNode['id'] > $maxId) { + $maxId = $scheduledNode['id']; + } + } + + return $maxId + 1; + } +}