Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Classes/Cache/StaticFileBackend.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,36 @@ public function has(string $entryIdentifier): bool
return is_file($this->getFilepath($entryIdentifier)) || parent::has($entryIdentifier);
}

/**
* Checks whether a generated file exists for the given entry identifier.
*
* In contrast to has(), the database entry does not count: has() is also
* true for an entry without file (e.g. after the cache directory was
* emptied), but only the file makes Apache deliver the page statically.
* Which file is written depends on the enabled generators (plain, gzip,
* brotli, php), so every variant counts.
*/
public function hasStaticFile(string $entryIdentifier): bool
{
try {
$fileName = $this->getFilepath($entryIdentifier);
} catch (\Throwable) {
return false;
}

if ('' === $fileName) {
return false;
}

foreach (['', '.gz', '.br', '.php'] as $suffix) {
if (is_file($fileName . $suffix)) {
return true;
}
}

return false;
}

/**
* Removes all cache entries matching the specified identifier.
* Usually this only affects one entry but if - for what reason ever -
Expand Down
23 changes: 22 additions & 1 deletion Classes/Middleware/GenerateMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SFC\Staticfilecache\Cache\StaticFileBackend;
use SFC\Staticfilecache\Event\PreGenerateEvent;
use SFC\Staticfilecache\Service\CacheService;
use SFC\Staticfilecache\Service\ConfigurationService;
Expand Down Expand Up @@ -98,6 +99,12 @@ protected function calculateLifetime(RequestInterface $request, ResponseInterfac
/**
* Determines whether the given $uri has a valid cache entry.
*
* The entry (database) is only valid together with the generated file. An
* entry without a file (e.g. the cache directory was emptied while the
* database table was not) would otherwise be reported as "already in cache"
* until it expires, and every request would be handled by PHP in the
* meantime, because nobody writes the file again.
*
* @param string $uri
*
* @return bool is available and valid
Expand All @@ -108,7 +115,21 @@ protected function hasValidCacheEntry($uri): bool

return false !== $entry
&& empty($entry['explanation'])
&& $entry['expires'] >= (new DateTimeService())->getCurrentTime();
&& $entry['expires'] >= (new DateTimeService())->getCurrentTime()
&& $this->hasStaticFile((string) $uri);
}

/**
* Determines whether the static file of the given $uri exists.
*
* Other backends than the StaticFileBackend know nothing about files, so
* the entry alone decides there.
*/
protected function hasStaticFile(string $uri): bool
{
$backend = $this->cache->getBackend();

return !$backend instanceof StaticFileBackend || $backend->hasStaticFile($uri);
}

/**
Expand Down
43 changes: 43 additions & 0 deletions Tests/Unit/Cache/StaticFileBackendTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,49 @@ public function testSetStoreEntryAndDispatchGeneratorEvents(): void
self::assertSame([self::URI], array_values($backend->findIdentifiersByTag('pageId_1')));
}

public function testHasStaticFileIsFalseForEntryWithoutFile(): void
{
$this->configure();
$backend = $this->getBackend();
$this->frontend->set(self::URI, new Response(), ['pageId_1'], 3600);

// The entry alone makes has() true, but there is nothing Apache could deliver.
self::assertTrue($backend->has(self::URI));
self::assertFalse($backend->hasStaticFile(self::URI));
}

/**
* @return array<string, array{string}>
*/
public static function generatedFileProvider(): array
{
return [
'plain' => ['index'],
'gzip' => ['index.gz'],
'brotli' => ['index.br'],
'php' => ['index.php'],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('generatedFileProvider')]
public function testHasStaticFileIsTrueForAnyGeneratedFile(string $file): void
{
$this->configure();
$backend = $this->getBackend();
$this->frontend->set(self::URI, new Response(), ['pageId_1'], 3600);
touch($this->cacheDirectory . 'https_www.example.com_443/page/' . $file);

self::assertTrue($backend->hasStaticFile(self::URI));
}

public function testHasStaticFileIsFalseForUnknownIdentifier(): void
{
$this->configure();

self::assertFalse($this->getBackend()->hasStaticFile('https://www.example.com/unknown/'));
self::assertFalse($this->getBackend()->hasStaticFile('invalid'));
}

public function testSetExplanationOnlyStoresDetails(): void
{
$this->configure();
Expand Down
35 changes: 35 additions & 0 deletions Tests/Unit/Middleware/GenerateMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace SFC\Staticfilecache\Tests\Unit\Middleware;

use PHPUnit\Framework\MockObject\MockObject;
use SFC\Staticfilecache\Cache\StaticFileBackend;
use SFC\Staticfilecache\Event\PreGenerateEvent;
use SFC\Staticfilecache\Middleware\GenerateMiddleware;
use SFC\Staticfilecache\Service\CacheService;
Expand Down Expand Up @@ -125,6 +126,32 @@ public function testValidCacheEntryIsNotStoredAgain(): void
self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State'));
}

public function testValidCacheEntryWithStaticFileIsNotStoredAgain(): void
{
$this->setExtensionConfiguration(['debugHeaders' => '1']);
$this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]);
$this->cache->method('getBackend')->willReturn($this->getStaticFileBackend(true));
$this->cache->expects(self::never())->method('set');
$this->cookieService->method('hasCookie')->willReturn(false);

$response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse()));

self::assertSame('TYPO3 - already in cache', $response->getHeaderLine('X-SFC-State'));
}

public function testValidCacheEntryWithoutStaticFileIsStoredAgain(): void
{
$this->setExtensionConfiguration(['debugHeaders' => '1']);
$this->cache->method('get')->willReturn(['explanation' => [], 'expires' => PHP_INT_MAX]);
$this->cache->method('getBackend')->willReturn($this->getStaticFileBackend(false));
$this->cache->expects(self::once())->method('set');
$this->cookieService->method('hasCookie')->willReturn(false);

$response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler($this->getCachableResponse()));

self::assertSame('TYPO3 - add to cache', $response->getHeaderLine('X-SFC-State'));
}

/**
* @return array<string, array{array{explanation: list<string>, expires: int}, bool}>
*/
Expand Down Expand Up @@ -170,6 +197,14 @@ public function testEventCanChangeUriAndResponse(): void
self::assertSame('yes', $response->getHeaderLine('X-Changed'));
}

protected function getStaticFileBackend(bool $hasStaticFile): StaticFileBackend&MockObject
{
$backend = $this->createMock(StaticFileBackend::class);
$backend->expects(self::once())->method('hasStaticFile')->with('https://example.com/page/')->willReturn($hasStaticFile);

return $backend;
}

protected function getCachableResponse(int $status = 200): HtmlResponse
{
return new HtmlResponse('<html></html>', $status, [
Expand Down
Loading