add json session repository

This commit is contained in:
Yisroel Baum 2026-04-24 13:22:19 +03:00
parent 619ebd3907
commit 762bbb7fda
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -0,0 +1,84 @@
<?php
namespace App\Auth;
use DateTimeImmutable;
class JsonSessionRepository implements SessionRepository
{
private string $filePath;
public function __construct()
{
$this->filePath = __DIR__ . '/../../data/sessions.json';
}
public function create(CreateSessionDto $dto): Session
{
$sessions = $this->readSessions();
$sessions[] = [
'token' => $dto->token,
'userId' => $dto->userId,
'createdAt' => $dto->createdAt->format(DATE_ATOM),
'expiresAt' => $dto->expiresAt->format(DATE_ATOM),
];
$this->writeSessions($sessions);
return new Session(
token: $dto->token,
userId: $dto->userId,
createdAt: $dto->createdAt,
expiresAt: $dto->expiresAt,
);
}
public function findByToken(string $token): ?Session
{
$sessions = $this->readSessions();
foreach ($sessions as $data) {
if ($data['token'] === $token) {
return new Session(
token: $data['token'],
userId: $data['userId'],
createdAt: new DateTimeImmutable($data['createdAt']),
expiresAt: new DateTimeImmutable($data['expiresAt']),
);
}
}
return null;
}
public function deleteByToken(string $token): void
{
$sessions = $this->readSessions();
$filtered = array_values(array_filter(
$sessions,
function (array $data) use ($token) {
return $data['token'] !== $token;
}
));
$this->writeSessions($filtered);
}
private function readSessions(): array
{
if (!file_exists($this->filePath)) {
return [];
}
$content = file_get_contents($this->filePath);
return json_decode($content, true) ?? [];
}
private function writeSessions(array $sessions): void
{
file_put_contents(
$this->filePath,
json_encode($sessions, JSON_PRETTY_PRINT)
);
}
}