3 declare(strict_types=1);
13 use Psr\Cache\CacheItemInterface;
14 use Psr\Cache\CacheItemPoolInterface;
15 use Psr\SimpleCache\CacheInterface;
35 $this->validateCache($cache);
36 $this->cache = $cache;
37 $this->provider = $provider;
38 $this->cacheKey = self::TOKEN_CACHE_KEY .
"_" . ($cacheKey ?? sha1(self::TOKEN_CACHE_KEY));
45 private function validateCache($cache): void
47 if (!$cache instanceof CacheInterface && !$cache instanceof CacheItemPoolInterface) {
59 $token = $this->getCacheToken();
60 if (!is_null($token)) {
72 $token = $this->provider->refreshToken();
74 $ttl = max(1, ($token->getExpiresIn() - 300));
76 $this->cache($token, $ttl);
81 private function getCacheToken(): ?string
83 $cache = $this->cache;
84 if ($cache instanceof CacheInterface) {
86 return $cache->get($this->cacheKey,
null);
89 $item = $cache->getItem($this->cacheKey);
91 return (
string)$item->get();
97 private function cache(Token $token,
int $ttl): void
99 $cache = $this->cache;
100 if ($cache instanceof CacheInterface) {
101 $cache->set($this->cacheKey, $token->getValue(), $ttl);
103 $item = $cache->getItem($this->cacheKey)->set($token->getValue())->expiresAfter($ttl);