1
0
mirror of https://github.com/danog/dns.git synced 2025-01-07 13:41:06 +01:00
dns/lib/Addr/MemoryCache.php

63 lines
1.4 KiB
PHP
Raw Normal View History

2014-06-15 23:52:02 +02:00
<?php
namespace Addr;
class MemoryCache implements Cache
{
/**
* Mapped names stored in the cache
*
* @var array
*/
private $data = [
AddressModes::INET4_ADDR => [],
AddressModes::INET6_ADDR => [],
];
/**
2014-06-16 19:30:28 +02:00
* Look up an entry in the cache
2014-06-15 23:52:02 +02:00
*
* @param string $name
2014-06-16 19:30:28 +02:00
* @param int $type
* @param callable $callback
2014-06-15 23:52:02 +02:00
*/
public function resolve($name, $type, callable $callback)
2014-06-15 23:52:02 +02:00
{
2014-07-20 01:15:33 +02:00
if (!isset($this->data[$type][$name]) || $this->data[$type][$name][1] < time()) {
2014-06-15 23:52:02 +02:00
unset($this->data[$type][$name]);
2014-07-20 01:15:33 +02:00
$callback(null);
} else {
$callback($this->data[$type][$name][0]);
2014-06-15 23:52:02 +02:00
}
}
/**
* 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]);
}
}
}
}
}