proxitok/app/Cache/JSONCache.php

34 lines
1 KiB
PHP
Raw Normal View History

2022-01-13 10:51:45 -05:00
<?php
2022-01-30 18:02:52 -05:00
namespace App\Cache;
2022-01-13 10:51:45 -05:00
class JSONCache {
2022-02-16 09:20:35 -05:00
private string $cache_path = __DIR__ . '/../../cache/api';
function __construct() {
2022-02-16 09:20:35 -05:00
if (isset($_ENV['API_CACHE_JSON']) && !empty($_ENV['API_CACHE_JSON'])) {
$this->cache_path = $_ENV['API_CACHE_JSON'];
}
}
2022-02-16 09:20:35 -05:00
public function get(string $cache_key): object|false {
$filename = $this->cache_path . '/' . $cache_key . '.json';
if (is_file($filename)) {
2022-02-16 09:20:35 -05:00
$time = time();
$json_string = file_get_contents($filename);
2022-01-13 10:51:45 -05:00
$element = json_decode($json_string);
2022-02-16 09:20:35 -05:00
if ($time < $element->expires) {
return $element->data;
}
// Remove file if expired
unlink($filename);
2022-01-13 10:51:45 -05:00
}
2022-02-16 09:20:35 -05:00
return false;
2022-01-13 10:51:45 -05:00
}
2022-02-16 09:20:35 -05:00
public function set(string $cache_key, mixed $data, $timeout = 3600) {
file_put_contents($this->cache_path . '/' . $cache_key . '.json', json_encode([
'data' => $data,
'expires' => time() + $timeout
]));
2022-01-13 10:51:45 -05:00
}
}