Goal-Calibration/app/Plan/JsonPlanRepository.php

118 lines
2.7 KiB
PHP

<?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;
}
public function findByUser(User $user): array
{
$plans = array_filter(
$this->readPlans(),
function ($data) use ($user) {
return $data['userId'] === $user->getId();
}
);
return array_map(
function ($data) {
$user = $this->userRepository->find($data['userId']);
if ($user === null) {
return null;
}
return new Plan(
id: $data['id'],
name: $data['name'],
user: $user,
);
},
$plans
);
}
}