add json session repository
This commit is contained in:
parent
619ebd3907
commit
762bbb7fda
1 changed files with 84 additions and 0 deletions
84
app/Auth/JsonSessionRepository.php
Normal file
84
app/Auth/JsonSessionRepository.php
Normal 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)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue