Passed
Pull Request — master (#15)
by Christian
04:47
created

Cached::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
namespace RemotelyLiving\PHPDNS\Resolvers;
3
4
use Psr\Cache\CacheItemPoolInterface;
5
use RemotelyLiving\PHPDNS\Entities\DNSRecordCollection;
6
use RemotelyLiving\PHPDNS\Entities\DNSRecordType;
7
use RemotelyLiving\PHPDNS\Entities\Hostname;
8
use RemotelyLiving\PHPDNS\Resolvers\Traits\Time;
9
use RemotelyLiving\PHPDNS\Resolvers\Interfaces\Resolver;
10
11
class Cached extends ResolverAbstract
12
{
13
    protected const DEFAULT_CACHE_TTL = 600;
14
    private const CACHE_KEY_TEMPLATE = '%s:%s:%s';
15
16
    use Time;
17
18
    /**
19
     * @var \Psr\Cache\CacheItemPoolInterface
20
     */
21
    private $cache;
22
23
    /**
24
     * @var \RemotelyLiving\PHPDNS\Resolvers\Interfaces\Resolver
25
     */
26
    private $resolver;
27
28
    /**
29
     * @var string
30
     */
31
    private $namespace = 'php-dns-v1';
32
33
    /**
34
     * @var int|null
35
     */
36
    private $ttlSeconds;
37
38
    /**
39
     * @var bool
40
     */
41
    private $shouldCacheEmptyResults = true;
42
43
    public function __construct(CacheItemPoolInterface $cache, Resolver $resolver, int $ttlSeconds = null)
44
    {
45
        $this->cache = $cache;
46
        $this->resolver = $resolver;
47
        $this->ttlSeconds = $ttlSeconds;
48
    }
49
50
    public function flush(): void
51
    {
52
        $this->cache->clear();
53
    }
54
55
    public function withEmptyResultCachingDisabled() : self
56
    {
57
        $emptyCachingDisabled = new static($this->cache, $this->resolver, $this->ttlSeconds);
58
        $emptyCachingDisabled->shouldCacheEmptyResults = false;
59
60
        return $emptyCachingDisabled;
61
    }
62
63
    protected function doQuery(Hostname $hostname, DNSRecordType $recordType): DNSRecordCollection
64
    {
65
        $cachedResult = $this->cache->getItem($this->buildCacheKey($hostname, $recordType));
66
67
        if ($cachedResult->isHit()) {
68
            return $this->unwrapResults($cachedResult->get());
69
        }
70
71
        $dnsRecords = $this->resolver->getRecords((string)$hostname, (string)$recordType);
72
        if ($dnsRecords->isEmpty() && $this->shouldCacheEmptyResults === false) {
73
            return $dnsRecords;
74
        }
75
76
        $ttlSeconds = $this->ttlSeconds ?? $this->extractLowestTTL($dnsRecords);
77
        $cachedResult->expiresAfter($ttlSeconds);
78
        $cachedResult->set(['recordCollection' => $dnsRecords, 'timestamp' => $this->getTimeStamp()]);
79
        $this->cache->save($cachedResult);
80
81
        return $dnsRecords;
82
    }
83
84
    private function buildCacheKey(Hostname $hostname, DNSRecordType $recordType): string
85
    {
86
        return md5(sprintf(self::CACHE_KEY_TEMPLATE, $this->namespace, (string)$hostname, (string)$recordType));
87
    }
88
89
    private function extractLowestTTL(DNSRecordCollection $recordCollection): int
90
    {
91
        $ttls = [];
92
93
        /** @var \RemotelyLiving\PHPDNS\Entities\DNSRecord $record */
94
        foreach ($recordCollection as $record) {
95
            /** @scrutinizer ignore-call */
96
            $ttls[] = $record->getTTL();
97
        }
98
99
        return count($ttls) ? min($ttls) : self::DEFAULT_CACHE_TTL;
100
    }
101
102
    /**
103
     * @param array $results ['recordCollection' => $recordCollection, 'timestamp' => $timeStamp]
104
     */
105
    private function unwrapResults(array $results) : DNSRecordCollection
106
    {
107
        $records = $results['recordCollection'];
108
        foreach ($records as $key => $record) {
109
            $records[$key] = $record
110
                ->setTTL($record->getTTL() - ($this->getTimeStamp() - (int)$results['timestamp']));
111
        }
112
113
        return $records;
114
    }
115
}
116