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
13 changes: 9 additions & 4 deletions src/FileAccess.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public function __construct(
}

public function getData(string $name):mixed {
$filePath = "$this->dirPath/$name";
$filePath = $this->getFilePath($name);
if(!is_file($filePath)) {
throw new FileNotFoundException($filePath);
}
Expand All @@ -18,15 +18,15 @@ public function getData(string $name):mixed {
}

public function setData(string $name, mixed $value):void {
$filePath = "$this->dirPath/$name";
$filePath = $this->getFilePath($name);
if(!is_dir(dirname($filePath))) {
mkdir(dirname($filePath), 0775, true);
}
file_put_contents($filePath, serialize($value));
}

public function checkValidity(string $name, int $secondsValidity):void {
$filePath = "$this->dirPath/$name";
$filePath = $this->getFilePath($name);
if(!is_file($filePath)) {
throw new CacheInvalidException("$filePath (does not exist)");
}
Expand All @@ -37,11 +37,16 @@ public function checkValidity(string $name, int $secondsValidity):void {
}

public function invalidate(string $name):void {
$filePath = "$this->dirPath/$name";
$filePath = $this->getFilePath($name);
if(!is_file($filePath)) {
return;
}

unlink($filePath);
}

private function getFilePath(string $name):string {
$escapedName = rawurlencode($name);
return "$this->dirPath/$escapedName";
}
}
27 changes: 27 additions & 0 deletions test/phpunit/CacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,33 @@ public function testGet_nullValueCanBeCached():void {
self::assertSame(1, $count);
}

public function testGet_urlName_isEscapedToReadableFilename():void {
$sut = $this->getSut();
$name = "https://example.com/test";
$value = "cached-value";

self::assertSame($value, $sut->get($name, fn() => $value));

$expectedFile = sys_get_temp_dir()
. "/phpgt-filecache/"
. rawurlencode($name);
self::assertFileExists($expectedFile);
self::assertSame($value, unserialize(file_get_contents($expectedFile)));
}

public function testGet_urlName_doesNotTraverseFilesystem():void {
$sut = $this->getSut();
$name = "../outside-cache";
$value = "cached-value";

self::assertSame($value, $sut->get($name, fn() => $value));

$cacheDir = sys_get_temp_dir() . "/phpgt-filecache";
$expectedFile = $cacheDir . "/" . rawurlencode($name);
self::assertFileExists($expectedFile);
self::assertFileDoesNotExist(sys_get_temp_dir() . "/outside-cache");
}

public function testGet_generationExceptionDoesNotWriteInvalidValue():void {
$fileAccess = self::createMock(FileAccess::class);
$fileAccess->expects(self::once())
Expand Down
Loading