Last active
December 13, 2016 21:51
-
-
Save JanTvrdik/f76d98b818abdde26cb4 to your computer and use it in GitHub Desktop.
General purpose thread-safe cache function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param string $file | |
* @param callable $tryLoad (string $file, mixed & $data): bool | |
* @param callable $isExpired (string $file): bool | |
* @param callable $fallback (string $file): string | |
* @return mixed | |
*/ | |
function loadCacheFile($file, $tryLoad, $isExpired, $fallback) | |
{ | |
if (!$isExpired($file) && $tryLoad($file, $data)) { | |
return $data; | |
} | |
if (!is_dir(dirname($file))) { | |
@mkdir(dirname($file)); // @ - directory may already exist | |
} | |
$handle = fopen("$file.lock", 'c+'); | |
if (!$handle || !flock($handle, LOCK_EX)) { | |
throw new \RuntimeException("Unable to acquire exclusive lock '$file.lock'."); | |
} | |
if (!is_file($file) || $isExpired($file)) { | |
$data = $fallback($file); | |
if (file_put_contents("$file.tmp", $data) !== strlen($data) || !rename("$file.tmp", $file)) { | |
@unlink("$file.tmp"); // @ - file may not exist | |
throw new \RuntimeException("Unable to create '$file'."); | |
} | |
} | |
if (!$tryLoad($file, $data)) { | |
throw new \RuntimeException("Unable to load '$file'."); | |
} | |
flock($handle, LOCK_UN); | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment