Psr16CacheStorage::save()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.2559

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
ccs 3
cts 5
cp 0.6
crap 2.2559
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