diff --git a/README.md b/README.md index d0b0c90..d96ff05 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,9 @@ Cache data in local files. Making expensive operations like HTTP calls or database queries can be minimised by caching the result of the operations in local files. This can improve performance, reduce network usage, and avoid rate limiting, to name some common benefits. This library provides a single function to define where to cache, what to cache, and when to cache. A validity of 1 hour is set by default, if the valid time is not specified. +Pass `secondsValid: 0` to the `Cache` constructor to cache indefinitely. The value +is kept until you call `invalidate($name)` or remove its cache file. + *** diff --git a/src/FileAccess.php b/src/FileAccess.php index dcd49e5..41d7277 100644 --- a/src/FileAccess.php +++ b/src/FileAccess.php @@ -30,6 +30,9 @@ public function checkValidity(string $name, int $secondsValidity):void { if(!is_file($filePath)) { throw new CacheInvalidException("$filePath (does not exist)"); } + if($secondsValidity === 0) { + return; + } $fileModifiedTimestamp = filemtime($filePath); if($fileModifiedTimestamp <= time() - $secondsValidity) { throw new CacheInvalidException($filePath); diff --git a/test/phpunit/CacheTest.php b/test/phpunit/CacheTest.php index cefcd9c..7596863 100644 --- a/test/phpunit/CacheTest.php +++ b/test/phpunit/CacheTest.php @@ -52,6 +52,44 @@ public function testGet_multipleCallsDoesNotCallbackMultipleTimes():void { self::assertSame(1, $count); } + public function testGet_zeroValidityCachesUntilInvalidated():void { + $sut = new Cache(sys_get_temp_dir() . "/phpgt-filecache", 0); + $count = 0; + $callback = function()use(&$count):int { + return ++$count; + }; + + self::assertSame(1, $sut->get("indefinite", $callback)); + self::assertSame(1, $sut->get("indefinite", $callback)); + self::assertSame(1, $count); + + $sut->invalidate("indefinite"); + self::assertSame(2, $sut->get("indefinite", $callback)); + } + + public function testGet_zeroValidityReadsOldCacheFromAnotherInstance():void { + $path = sys_get_temp_dir() . "/phpgt-filecache"; + $sut = new Cache($path, 0); + self::assertSame("original", $sut->get("indefinite", fn() => "original")); + self::assertTrue(touch("$path/indefinite", time() - 31536000)); + clearstatcache(); + + $sut = new Cache($path, 0); + self::assertSame("original", $sut->get("indefinite", function():never { + self::fail("An indefinite cache must not regenerate an old value."); + })); + } + + public function testGet_positiveValidityRegeneratesExpiredCache():void { + $path = sys_get_temp_dir() . "/phpgt-filecache"; + $sut = new Cache($path, 60); + self::assertSame("original", $sut->get("expired", fn() => "original")); + self::assertTrue(touch("$path/expired", time() - 120)); + clearstatcache(); + + self::assertSame("replacement", $sut->get("expired", fn() => "replacement")); + } + public function testGet_nullValueCanBeCached():void { $sut = $this->getSut(); $count = 0;