Psr16CacheStorage::getCacheKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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\SimpleCache\CacheInterface;
17
use Psr\SimpleCache\InvalidArgumentException;
18
19
class Psr16CacheStorage implements StorageInterface
20
{
21
    /** @var CacheInterface */
22
    private $cache;
23
24 1
    public function __construct(CacheInterface $cache)
25
    {
26 1
        $this->cache = $cache;
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->cache->get($cacheKey);
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,InvalidArgument */
52
        try {
53 1
            $this->cache->set($cacheKey, $dnsRecord, $dnsRecord->getTTL());
54
        } catch (InvalidArgumentException $e) {
55
            throw new \RuntimeException('Invalid cache key ' . $cacheKey, 0, $e);
56
        }
57
    }
58
59 1
    private function getCacheKey(string $domainName): string
60
    {
61 1
        return rawurlencode('guzzle.doh.psr16.' . $domainName);
62
    }
63
}
64