add json scheduled node repository
This commit is contained in:
parent
3595bcbf11
commit
baf12500c7
1 changed files with 67 additions and 0 deletions
67
app/ScheduledNode/JsonScheduledNodeRepository.php
Normal file
67
app/ScheduledNode/JsonScheduledNodeRepository.php
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
<?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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue