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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
<?php
namespace Commercetools\Core\Client\OAuth;
use Psr\Cache\CacheItemPoolInterface;
use Psr\SimpleCache\CacheInterface;
class CacheTokenProvider implements RefreshTokenProvider
{
const TOKEN_CACHE_KEY = 'commercetools_io_access_token';
private $tokenProvider;
private $cache;
private $cacheKey;
public function __construct(RefreshTokenProvider $tokenProvider, $cache, $cacheKey = null)
{
$this->tokenProvider = $tokenProvider;
$this->cache = $cache;
$this->cacheKey = self::TOKEN_CACHE_KEY . "_" . (!is_null($cacheKey) ? $cacheKey : sha1('access_token'));
}
public function getToken()
{
$item = null;
$token = $this->getCacheToken();
if (!is_null($token)) {
return new Token($token);
}
return $this->refreshToken();
}
public function refreshToken()
{
$token = $this->tokenProvider->refreshToken();
$ttl = max(1, floor($token->getTtl()/2));
$this->cache($token, $ttl);
return $token;
}
private function getCacheToken()
{
$cache = $this->cache;
if ($cache instanceof CacheInterface) {
$var = $cache->get($this->cacheKey, null);
return $var;
} elseif ($cache instanceof CacheItemPoolInterface) {
$item = $cache->getItem($this->cacheKey);
if ($item->isHit()) {
return $item->get();
}
}
return null;
}
private function cache(Token $token, $ttl)
{
$cache = $this->cache;
if ($cache instanceof CacheInterface) {
$cache->set($this->cacheKey, $token->getToken(), (int)$ttl);
} elseif ($cache instanceof CacheItemPoolInterface) {
$item = $cache->getItem($this->cacheKey)->set($token->getToken())->expiresAfter((int)$ttl);
$cache->save($item);
}
}
}