84 lines
2.1 KiB
PHP
84 lines
2.1 KiB
PHP
<?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)
|
|
);
|
|
}
|
|
}
|