commercetools-sdk-php-v2
The commercetools platform, import-api and PHP sdks generated from our api reference.
All Classes Namespaces Functions Variables Pages
CachedTokenProvider.php
1<?php
2
3declare(strict_types=1);
10namespace Commercetools\Client;
11
13use Psr\Cache\CacheItemInterface;
14use Psr\Cache\CacheItemPoolInterface;
15use 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 $token = $this->getCacheToken();
58 if (!is_null($token)) {
59 return new TokenModel($token);
60 }
61
62 return $this->refreshToken();
63 }
64
68 public function refreshToken(): Token
69 {
70 $token = $this->provider->refreshToken();
71 // ensure token to be invalidated in cache before TTL
72 $ttl = max(1, ($token->getExpiresIn() - 300));
73
74 $this->cache($token, $ttl);
75
76 return $token;
77 }
78
79 private function getCacheToken(): ?string
80 {
81 $cache = $this->cache;
82 if ($cache instanceof CacheInterface) {
84 return $cache->get($this->cacheKey, null);
85 }
86
87 $item = $cache->getItem($this->cacheKey);
88 if ($item->isHit()) {
89 return (string)$item->get();
90 }
91
92 return null;
93 }
94
95 private function cache(Token $token, int $ttl): void
96 {
97 $cache = $this->cache;
98 if ($cache instanceof CacheInterface) {
99 $cache->set($this->cacheKey, $token->getValue(), $ttl);
100 } else {
101 $item = $cache->getItem($this->cacheKey)->set($token->getValue())->expiresAfter($ttl);
102 $cache->save($item);
103 }
104 }
105}
__construct(TokenProvider $provider, $cache, ?string $cacheKey=null)