summaryrefslogtreecommitdiff
path: root/src/TokenStorage.php
blob: d7b8db86c6c06480fde826a240402cf26bf3b8d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

declare(strict_types=1);

namespace TCB;

final class TokenStorage
{
    public function __construct(
        public string $accessToken,
        public string $refreshToken,
        public int $expiresOn,
        private readonly string $filename,
    ) {}

    static public function load(string $filename): self
    {
        $storage = is_readable($filename)
            ? json_decode(file_get_contents($filename), true)
            : [];

        return new self(
            accessToken: $storage['accessToken'] ?? '',
            refreshToken: $storage['refreshToken'] ?? '',
            expiresOn: $storage['expiresOn'] ?? 0,
            filename: $filename,
        );
    }

    public function save(): void
    {
        file_put_contents($this->filename, json_encode($this, JSON_PRETTY_PRINT));
    }
}