From a64903be1d78c233ee17365a0c311c72539fb35a Mon Sep 17 00:00:00 2001 From: otsch Date: Wed, 20 Dec 2023 02:09:22 +0100 Subject: [PATCH] Fix reading uncompressed files When FileCache compression is activated, the FileCache assumed that all cache files that it will read are compressed. But there could be existing cache files created without compression activated which lead to errors. The FileCache now first checks if the content is compressed and only tries to decode if it is. --- CHANGELOG.md | 4 ++++ src/Cache/FileCache.php | 6 ++++++ tests/Cache/FileCacheTest.php | 24 ++++++++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f672a8..4bce1a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [1.3.5] - 2023-12-20 +### Fixed +* The `FileCache` can now also read uncompressed cache files when compression is activated. + ## [1.3.4] - 2023-12-19 ### Fixed * Reset paginator state after finishing paginating for one base input, to enable paginating multiple listings of the same structure. diff --git a/src/Cache/FileCache.php b/src/Cache/FileCache.php index 6c61786..8ed4dd0 100644 --- a/src/Cache/FileCache.php +++ b/src/Cache/FileCache.php @@ -209,6 +209,12 @@ protected function encode(string $content): string */ protected function decode(string $content): string { + $isEncoded = 0 === mb_strpos($content, "\x1f" . "\x8b" . "\x08", 0, "US-ASCII"); + + if (!$isEncoded) { + return $content; + } + if (!function_exists('gzdecode')) { throw new MissingZlibExtensionException('FileCache compression needs PHP ext-zlib installed.'); } diff --git a/tests/Cache/FileCacheTest.php b/tests/Cache/FileCacheTest.php index 92e2e14..99ac56d 100644 --- a/tests/Cache/FileCacheTest.php +++ b/tests/Cache/FileCacheTest.php @@ -300,6 +300,30 @@ function helper_respondedRequestWithRequestUrl(string $requestUrl): RespondedReq expect(Http::getBodyString($retrievedCacheItem))->toBe('Hello World'); }); +it('is also able to decode uncompressed cache files when useCompression() is used', function () { + $cache = new FileCache(helper_cachedir()); + + $respondedRequest = new RespondedRequest(new Request('GET', '/yo'), new Response(body: Utils::streamFor('Yo'))); + + $cache->set($respondedRequest->cacheKey(), $respondedRequest); + + $retrievedCacheItem = $cache->get($respondedRequest->cacheKey()); + + expect($retrievedCacheItem) + ->toBeInstanceOf(RespondedRequest::class) + ->and(Http::getBodyString($retrievedCacheItem)) + ->toBe('Yo'); + + $cache->useCompression(); + + $retrievedCacheItem = $cache->get($respondedRequest->cacheKey()); + + expect($retrievedCacheItem) + ->toBeInstanceOf(RespondedRequest::class) + ->and(Http::getBodyString($retrievedCacheItem)) + ->toBe('Yo'); +}); + test('you can change the default ttl', function () { $cache = new FileCache(helper_cachedir());