add json plan repository
This commit is contained in:
parent
e1b02f0ba9
commit
895bfb01da
1 changed files with 93 additions and 0 deletions
93
app/Plan/JsonPlanRepository.php
Normal file
93
app/Plan/JsonPlanRepository.php
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue