-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheProvider.php
89 lines (76 loc) · 2.26 KB
/
CacheProvider.php
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
<?php
namespace Wearesho\Phonet\Authorization;
use GuzzleHttp;
use Psr\SimpleCache\CacheInterface;
use Wearesho\Phonet\ConfigInterface;
/**
* Class CacheProvider
* @package Wearesho\Phonet\Authorization
*/
class CacheProvider extends Provider implements CacheProviderInterface
{
/** @var CacheInterface */
protected $cache;
public function __construct(CacheInterface $cache, GuzzleHttp\ClientInterface $client)
{
$this->cache = $cache;
parent::__construct($client);
}
/**
* @param ConfigInterface $config
*
* @return string
* @throws ProviderException
*/
public function provide(ConfigInterface $config): string
{
$key = $this->getCacheKey($config);
try {
$cached = $this->cache->get($key);
} catch (\Psr\SimpleCache\InvalidArgumentException $exception) {
throw new CacheException($key, null, $exception->getMessage(), $exception->getCode(), $exception);
}
if (!$cached) {
return $this->forceProvide($config);
}
return $cached;
}
/**
* @param ConfigInterface $config
*
* @return string
* @throws ProviderException
*/
public function forceProvide(ConfigInterface $config): string
{
$cacheKey = $this->getCacheKey($config);
$sessionId = parent::provide($config);
$this->cacheResponse($cacheKey, $sessionId);
return $sessionId;
}
/**
* @param string $cacheKey
* @param string $sessionId
*/
protected function cacheResponse(string $cacheKey, string $sessionId): void
{
try {
$isCacheSet = $this->cache->set($cacheKey, $sessionId);
} catch (\Psr\SimpleCache\InvalidArgumentException $exception) {
throw new CacheException(
$cacheKey,
$sessionId,
$exception->getMessage(),
$exception->getCode(),
$exception
);
}
if (!$isCacheSet) {
throw new CacheException($cacheKey, $sessionId);
}
}
protected function getCacheKey(ConfigInterface $config): string
{
return "phonet.authorization." . sha1($config->getDomain() . $config->getApiKey());
}
}