Lines 100.00% 21 / 21
Methods 100.00% 4 / 4
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 store 100.00% 4 / 4 100.00% 1 / 1 2
 get 100.00% 7 / 7 100.00% 1 / 1 4
 fromSession 100.00% 9 / 9 100.00% 1 / 1 6
16final readonly class ApiTokenStore
17{
18    private const string SESSION_KEY = 'api_token';
19
20    public function __construct(
21        #[Autowire(env: 'bool:APP_FAKE_GOOGLE_TOKENS')] private bool $fakeTokensEnabled,
22    ) {
23    }
24
25    /**
26     * @param array<string, mixed> $payload the verified token payload
27     */
28    public function store(SessionInterface $session, string $idToken, array $payload): void
29    {
30        $session->set(self::SESSION_KEY, [
31            'token' => $idToken,
32            'expiresAt' => \is_int($payload['exp'] ?? null) ? $payload['exp'] : null,
33        ]);
34    }
35
36    public function get(SessionInterface $session, User $user): ?ApiToken
37    {
38        $apiToken = $this->fromSession($session);
39        if ($apiToken instanceof ApiToken) {
40            return $apiToken;
41        }
42
43        $googleId = $user->getGoogleId();
44        if ($this->fakeTokensEnabled && null !== $googleId) {
45            return new ApiToken(FakeGoogleIdTokenVerifier::token($googleId, $user->getIdentifier()), null, true);
46        }
47
48        return null;
49    }
50
51    /**
52     * The stored token, unless it has expired.
53     */
54    private function fromSession(SessionInterface $session): ?ApiToken
55    {
56        $stored = $session->get(self::SESSION_KEY);
57        if (!\is_array($stored) || !\is_string($stored['token'] ?? null)) {
58            return null;
59        }
60
61        $expiresAt = \is_int($stored['expiresAt'] ?? null)
62            ? new \DateTimeImmutable('@'.$stored['expiresAt'])
63            : null;
64
65        return !$expiresAt instanceof \DateTimeImmutable || $expiresAt > new \DateTimeImmutable()
66            ? new ApiToken($stored['token'], $expiresAt)
67            : null;
68    }
69}