1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* Copyright (c) Ne-Lexa |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view |
9
|
|
|
* the LICENSE file that was distributed with this source code. |
10
|
|
|
* |
11
|
|
|
* @see https://github.com/Ne-Lexa/guzzle-doh-middleware |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Nelexa\Doh\Storage; |
15
|
|
|
|
16
|
|
|
use Psr\Cache\CacheItemPoolInterface; |
17
|
|
|
use Psr\Cache\InvalidArgumentException; |
18
|
|
|
|
19
|
|
|
class Psr6CacheStorage implements StorageInterface |
20
|
|
|
{ |
21
|
|
|
/** @var CacheItemPoolInterface */ |
22
|
|
|
private $cachePool; |
23
|
|
|
|
24
|
1 |
|
public function __construct(CacheItemPoolInterface $cachePool) |
25
|
|
|
{ |
26
|
1 |
|
$this->cachePool = $cachePool; |
27
|
|
|
} |
28
|
|
|
|
29
|
1 |
|
public function get(string $domainName): ?DnsRecord |
30
|
|
|
{ |
31
|
1 |
|
$cacheKey = $this->getCacheKey($domainName); |
32
|
|
|
|
33
|
|
|
/** @psalm-suppress InvalidCatch */ |
34
|
|
|
try { |
35
|
1 |
|
$dnsRecord = $this->cachePool->getItem($cacheKey)->get(); |
36
|
|
|
|
37
|
1 |
|
if (!$dnsRecord instanceof DnsRecord) { |
38
|
1 |
|
return null; |
39
|
|
|
} |
40
|
|
|
|
41
|
1 |
|
return $dnsRecord; |
42
|
|
|
} catch (InvalidArgumentException $e) { |
43
|
|
|
throw new \RuntimeException('Invalid cache key ' . $cacheKey, 0, $e); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
public function save(string $domainName, DnsRecord $dnsRecord): void |
48
|
|
|
{ |
49
|
1 |
|
$cacheKey = $this->getCacheKey($domainName); |
50
|
|
|
|
51
|
|
|
/** @psalm-suppress InvalidCatch */ |
52
|
|
|
try { |
53
|
1 |
|
$cacheItem = $this->cachePool->getItem($cacheKey); |
54
|
1 |
|
$cacheItem->expiresAfter($dnsRecord->getTTL()); |
55
|
1 |
|
$cacheItem->set($dnsRecord); |
56
|
1 |
|
$this->cachePool->save($cacheItem); |
57
|
|
|
} catch (InvalidArgumentException $e) { |
58
|
|
|
throw new \RuntimeException('Invalid cache key ' . $cacheKey, 0, $e); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
1 |
|
private function getCacheKey(string $domainName): string |
63
|
|
|
{ |
64
|
1 |
|
return rawurlencode('guzzle.doh.psr6.' . $domainName); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|