-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSR6CacheAdapter.php
More file actions
104 lines (80 loc) · 2.58 KB
/
Copy pathPSR6CacheAdapter.php
File metadata and controls
104 lines (80 loc) · 2.58 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
/*
* @author Aaron Scherer <aequasi@gmail.com>
* @date 2019
* @license https://opensource.org/licenses/MIT
*/
namespace Secretary\Adapter\Cache\PSR6Cache;
use Psr\Cache\CacheItemPoolInterface;
use Secretary\Adapter\AbstractAdapter;
use Secretary\Adapter\AdapterInterface;
use Secretary\Helper\ArrayHelper;
use Secretary\Secret;
/**
* Class PSR6CacheAdapter.
*
* @package Secretary\Adapter\Cache
*/
final class PSR6CacheAdapter extends AbstractAdapter
{
private AdapterInterface $adapter;
private CacheItemPoolInterface $cache;
public function __construct(AdapterInterface $adapter, CacheItemPoolInterface $cache)
{
$this->adapter = $adapter;
$this->cache = $cache;
}
/**
* {@inheritdoc}
*/
public function getSecret(string $key, ?array $options = []): Secret
{
['ttl' => $ttl] = ArrayHelper::remove($options, 'ttl');
$item = $this->cache->getItem(sha1($key));
if ($item->isHit()) {
[$value, $metadata] = json_decode($item->get(), true);
return new Secret($key, $value, $metadata);
}
$secret = $this->adapter->getSecret($key, $options);
$item->set(json_encode([$secret->getValue(), $secret->getMetadata()]));
if ($ttl !== null) {
$item->expiresAfter($ttl);
}
$this->cache->save($item);
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->hasItem(sha1($secret->getKey())) || $ttl === 0) {
$this->cache->deleteItem(sha1($secret->getKey()));
return $secret;
}
$item = $this->cache->getItem(sha1($secret->getKey()));
$item->set(json_encode([$secret->getValue(), $secret->getMetadata()]));
if (!empty($ttl)) {
$item->expiresAfter($ttl);
}
$this->cache->save($item);
return $secret;
}
/**
* {@inheritdoc}
*/
public function deleteSecret(Secret $secret, ?array $options = []): void
{
$this->deleteSecretByKey($secret->getKey(), $options);
}
public function deleteSecretByKey(string $key, ?array $options = []): void
{
$this->adapter->deleteSecret($this->adapter->getSecret($key, $options), $options);
if ($this->cache->hasItem(sha1($key))) {
$this->cache->deleteItem(sha1($key));
}
}
}