Refactored RuntimeCache.php

This commit is contained in:
Netkas 2023-10-03 17:34:09 -04:00
parent 021d5ec750
commit 8549cff119
No known key found for this signature in database
GPG key ID: 5DAF58535614062B
2 changed files with 10 additions and 72 deletions

View file

@ -85,7 +85,6 @@
try try
{ {
RuntimeCache::clearCache();
Functions::finalizePermissions(); Functions::finalizePermissions();
} }
catch (Exception $e) catch (Exception $e)

View file

@ -36,21 +36,14 @@
*/ */
private static $cache = []; private static $cache = [];
/**
* An array of files to delete when the cache is cleared
*
* @var string[]
*/
private static $temporary_files = [];
/** /**
* Sets a value, returns the value * Sets a value, returns the value
* *
* @param $key * @param string $key
* @param $value * @param $value
* @return mixed * @return mixed
*/ */
public static function set($key, $value): mixed public static function set(string $key, mixed $value): mixed
{ {
self::$cache[$key] = $value; self::$cache[$key] = $value;
return $value; return $value;
@ -59,76 +52,22 @@
/** /**
* Gets an existing value, null if it doesn't exist * Gets an existing value, null if it doesn't exist
* *
* @param $key * @param string $key
* @return mixed|null * @return mixed|null
*/ */
public static function get($key): mixed public static function get(string $key): mixed
{ {
if(isset(self::$cache[$key])) return self::$cache[$key] ?? null;
return self::$cache[$key];
return null;
} }
/** /**
* Sets a file as temporary, it will be deleted when the cache is cleared * Returns True if the key exists
* *
* @param string $path * @param string $key
* @return void * @return bool
*/ */
public static function setFileAsTemporary(string $path): void public static function exists(string $key): bool
{ {
Console::outDebug($path); return isset(self::$cache[$key]);
if(!in_array($path, self::$temporary_files))
self::$temporary_files[] = $path;
}
/**
* Removes a file from the temporary files list
*
* @param string $path
* @return void
* @noinspection PhpUnused
*/
public static function removeFileAsTemporary(string $path): void
{
Console::outDebug($path);
if(in_array($path, self::$temporary_files))
unset(self::$temporary_files[array_search($path, self::$temporary_files)]);
}
/**
* @param bool $clear_memory
* @param bool $clear_files
* @return void
*/
public static function clearCache(bool $clear_memory=true, bool $clear_files=true): void
{
Console::outDebug('clearing cache');
if($clear_memory)
{
Console::outDebug(sprintf('clearing memory cache (%d entries)', count(self::$cache)));
self::$cache = [];
}
if($clear_files)
{
Console::outDebug('clearing temporary files');
$filesystem = new Filesystem();
foreach(self::$temporary_files as $file)
{
try
{
$filesystem->remove($file);
Console::outDebug(sprintf('deleted temporary file \'%s\'', $file));
}
catch (Exception $e)
{
Console::outDebug(sprintf('failed to delete temporary file \'%s\', %s', $file, $e->getMessage()));
unset($e);
}
}
}
} }
} }