diff --git a/cache.php b/cache.php new file mode 100644 index 0000000..dbe643d --- /dev/null +++ b/cache.php @@ -0,0 +1,60 @@ +cacheDir = $cacheDir; + $this->defaultExpiration = $defaultExpiration; + // Create the cache directory if it doesn't exist + if (!file_exists($this->cacheDir)) { + mkdir($this->cacheDir, 0755, true); + } + } + + public function get($key, $expiration = null) + { + $file = $this->cacheDir . '/' . md5($key) . '.cache'; + if (file_exists($file)) { + $expiration = $expiration ?? $this->defaultExpiration; + if (time() - filemtime($file) < $expiration) { + $data = file_get_contents($file); + return unserialize($data); + } else { + unlink($file); + } + } + return null; + } + + public function set($key, $data): void + { + $file = $this->cacheDir . '/' . md5($key) . '.cache'; + file_put_contents($file, serialize($data)); + } + + public function delete($key): void + { + $file = $this->cacheDir . '/' . md5($key) . '.cache'; + if (file_exists($file)) { + unlink($file); + } + } + + public function clear() + { + array_map('unlink', glob($this->cacheDir . '/*.cache')); + } + + public function getOrSet($key, callable $callback, ?int $expiration = null) + { + $data = $this->get($key, $expiration); + if ($data === null) { + $data = $callback(); // Execute the callback to get the data + $this->set($key, $data); + } + return $data; + } +} \ No newline at end of file diff --git a/coingecko.php b/coingecko.php index 313e15d..d021370 100644 --- a/coingecko.php +++ b/coingecko.php @@ -6,14 +6,16 @@ date_default_timezone_set('Europe/Berlin'); // Define currencies that should *not* be included in the list $excludedCurrencies = ['bits', 'sats']; +require_once __DIR__ . '/cache.php'; + // Fetch JSON data from a file and decode it function fetchJson($filename) { return json_decode(file_get_contents($filename), true); } -function fetchCache(string $key, string $url) +function fetchCache(string $key, string $url, FileCache $cache) { - return apcu_entry($key, function() use ($url) { + return $cache->getOrSet($key, function() use ($url) { return makeApiRequest($url); }, 60); } @@ -78,8 +80,9 @@ function fetchAvailableCurrencies() { // Fetch currency data from CoinGecko API function fetchCurrencyData($currencies) { + $cache = new FileCache(__DIR__ . '/cache'); $apiUrl = getCoinGeckoApiUrl('simple/price', ['ids' => 'monero', 'vs_currencies' => implode(',', array_map('strtolower', $currencies))]); - return fetchCache('currency_data', $apiUrl); + return fetchCache('currency_data', $apiUrl, $cache); } $currencyFile = 'coingecko.json';