commercetools-sdk-php-v2
The commercetools platform, import-api and PHP sdks generated from our api reference.
CachedTokenProvider.php
1 <?php
2 
3 declare(strict_types=1);
10 namespace Commercetools\Client;
11 
13 use Psr\Cache\CacheItemInterface;
14 use Psr\Cache\CacheItemPoolInterface;
15 use Psr\SimpleCache\CacheInterface;
16 
18 {
19  public const TOKEN_CACHE_KEY = 'access_token';
20 
22  private $provider;
23 
25  private $cache;
26 
28  private $cacheKey;
29 
33  public function __construct(TokenProvider $provider, $cache, string $cacheKey = null)
34  {
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));
39  }
40 
45  private function validateCache($cache): void
46  {
47  if (!$cache instanceof CacheInterface && !$cache instanceof CacheItemPoolInterface) {
48  throw new InvalidArgumentException();
49  }
50  }
51 
55  public function getToken(): Token
56  {
57  $item = null;
58 
59  $token = $this->getCacheToken();
60  if (!is_null($token)) {
61  return new TokenModel($token);
62  }
63 
64  return $this->refreshToken();
65  }
66 
70  public function refreshToken(): Token
71  {
72  $token = $this->provider->refreshToken();
73  // ensure token to be invalidated in cache before TTL
74  $ttl = max(1, ($token->getExpiresIn() - 300));
75 
76  $this->cache($token, $ttl);
77 
78  return $token;
79  }
80 
81  private function getCacheToken(): ?string
82  {
83  $cache = $this->cache;
84  if ($cache instanceof CacheInterface) {
86  return $cache->get($this->cacheKey, null);
87  }
88 
89  $item = $cache->getItem($this->cacheKey);
90  if ($item->isHit()) {
91  return (string)$item->get();
92  }
93 
94  return null;
95  }
96 
97  private function cache(Token $token, int $ttl): void
98  {
99  $cache = $this->cache;
100  if ($cache instanceof CacheInterface) {
101  $cache->set($this->cacheKey, $token->getValue(), $ttl);
102  } else {
103  $item = $cache->getItem($this->cacheKey)->set($token->getValue())->expiresAfter($ttl);
104  $cache->save($item);
105  }
106  }
107 }
__construct(TokenProvider $provider, $cache, string $cacheKey=null)