Skip to content

Commit

Permalink
Fix reading uncompressed files
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
otsch committed Dec 20, 2023
1 parent e1b96ad commit a64903b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/Cache/FileCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
}
Expand Down
24 changes: 24 additions & 0 deletions tests/Cache/FileCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand Down

0 comments on commit a64903b

Please sign in to comment.