Goal-Calibration/app/ScheduledNode/JsonScheduledNodeRepository.php

67 lines
1.6 KiB
PHP

<?php
namespace App\ScheduledNode;
class JsonScheduledNodeRepository implements ScheduledNodeRepository
{
private string $filePath;
public function __construct()
{
$this->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;
}
}