108 lines
2.8 KiB
PHP
108 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\ScheduledNode;
|
|
|
|
use App\Node\NodeRepository;
|
|
use App\Plan\PlanRepository;
|
|
use App\User\User;
|
|
use DateTimeImmutable;
|
|
|
|
class JsonScheduledNodeRepository implements ScheduledNodeRepository
|
|
{
|
|
private string $filePath;
|
|
|
|
public function __construct(
|
|
private PlanRepository $planRepo,
|
|
private NodeRepository $nodeRepo,
|
|
) {
|
|
$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(),
|
|
'nodeId' => $dto->node->getId(),
|
|
'completed' => false,
|
|
];
|
|
$this->writeScheduledNodes($scheduledNodes);
|
|
|
|
return new ScheduledNode(
|
|
id: $id,
|
|
date: $dto->date,
|
|
plan: $dto->plan,
|
|
node: $dto->node,
|
|
completed: false,
|
|
);
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
public function findByUser(User $user): array
|
|
{
|
|
$allScheduledNodes = $this->readScheduledNodes();
|
|
$planIds = array_map(
|
|
function ($plan) {
|
|
return $plan->getId();
|
|
},
|
|
$this->planRepo->findByUser($user)
|
|
);
|
|
$usersScheduledNodes = array_filter(
|
|
$allScheduledNodes,
|
|
function ($node) use ($planIds) {
|
|
return in_array($node['planId'], $planIds);
|
|
}
|
|
);
|
|
|
|
return array_map(
|
|
function ($data) {
|
|
return new ScheduledNode(
|
|
id: $data['id'],
|
|
date: new DateTimeImmutable($data['date']),
|
|
plan: $this->planRepo->find($data['planId']),
|
|
node: $this->nodeRepo->find($data['nodeId']),
|
|
completed: $data['completed']
|
|
);
|
|
},
|
|
$usersScheduledNodes
|
|
);
|
|
}
|
|
}
|