add json plan repository

This commit is contained in:
Yisroel Baum 2026-04-24 10:24:39 +03:00
parent e1b02f0ba9
commit 895bfb01da
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -0,0 +1,93 @@
<?php
namespace App\Plan;
use App\User\User;
use App\User\UserRepository;
use App\ValueObjects\EmailAddress;
class JsonPlanRepository implements PlanRepository
{
private string $filePath;
public function __construct(
private UserRepository $userRepository,
) {
$this->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;
}
}