1
0
mirror of https://github.com/danog/dns.git synced 2025-01-05 20:48:35 +01:00
dns/lib/Addr/MemoryCache.php
2014-07-20 00:15:33 +01:00

63 lines
1.4 KiB
PHP

<?php
namespace Addr;
class MemoryCache implements Cache
{
/**
* Mapped names stored in the cache
*
* @var array
*/
private $data = [
AddressModes::INET4_ADDR => [],
AddressModes::INET6_ADDR => [],
];
/**
* Look up an entry in the cache
*
* @param string $name
* @param int $type
* @param callable $callback
*/
public function resolve($name, $type, callable $callback)
{
if (!isset($this->data[$type][$name]) || $this->data[$type][$name][1] < time()) {
unset($this->data[$type][$name]);
$callback(null);
} else {
$callback($this->data[$type][$name][0]);
}
}
/**
* Store an entry in the cache
*
* @param string $name
* @param string $addr
* @param int $type
* @param int $ttl
*/
public function store($name, $addr, $type, $ttl)
{
$this->data[$type][$name] = [$addr, time() + $ttl];
}
/**
* Remove expired records from the cache
*/
public function collectGarbage()
{
$now = time();
foreach ([AddressModes::INET4_ADDR, AddressModes::INET6_ADDR] as $type) {
while (list($name, $data) = each($this->data[$type])) {
if ($data[1] < $now) {
unset($this->data[$type][$name]);
}
}
}
}
}