-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSR16CacheAdapter.php
More file actions
89 lines (69 loc) · 2.25 KB
/
Copy pathPSR16CacheAdapter.php
File metadata and controls
89 lines (69 loc) · 2.25 KB
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
declare(strict_types=1);
/*
* @author Aaron Scherer <aequasi@gmail.com>
* @date 2019
* @license https://opensource.org/licenses/MIT
*/
namespace Secretary\Adapter\Cache\PSR16Cache;
use Psr\SimpleCache\CacheInterface;
use Secretary\Adapter\AbstractAdapter;
use Secretary\Adapter\AdapterInterface;
use Secretary\Helper\ArrayHelper;
use Secretary\Secret;
/**
* @package Secretary\Adapter\Cache
*/
final class PSR16CacheAdapter extends AbstractAdapter
{
private AdapterInterface $adapter;
private CacheInterface $cache;
public function __construct(AdapterInterface $adapter, CacheInterface $cache)
{
$this->adapter = $adapter;
$this->cache = $cache;
}
/**
* {@inheritdoc}
*/
public function getSecret(string $key, ?array $options = []): Secret
{
['ttl' => $ttl] = ArrayHelper::remove($options, 'ttl');
if ($this->cache->has(sha1($key))) {
[$value, $metadata] = json_decode($this->cache->get(sha1($key)), true);
return new Secret($key, $value, $metadata);
}
$secret = $this->adapter->getSecret($key, $options);
$this->cache->set(sha1($key), json_encode([$secret->getValue(), $secret->getMetadata()]), $ttl);
return $secret;
}
/**
* {@inheritdoc}
*/
public function putSecret(Secret $secret, ?array $options = []): Secret
{
['ttl' => $ttl] = ArrayHelper::remove($options, 'ttl');
$this->adapter->putSecret($secret, $options);
if ($this->cache->has(sha1($secret->getKey())) || $ttl === 0) {
$this->cache->delete(sha1($secret->getKey()));
return $secret;
}
$this->cache->set(sha1($secret->getKey()), json_encode([$secret->getValue(), $secret->getMetadata()]), $ttl);
return $secret;
}
/**
* {@inheritdoc}
*/
public function deleteSecret(Secret $secret, ?array $options = []): void
{
$this->deleteSecretByKey($secret->getKey(), $options);
}
/**
* {@inheritdoc}
*/
public function deleteSecretByKey(string $key, ?array $options = []): void
{
$this->adapter->deleteSecret($this->adapter->getSecret($key, $options), $options);
$this->cache->delete(sha1($key));
}
}