From c1ae9715b7e9f31007c82bd90cac70cca2284b20 Mon Sep 17 00:00:00 2001 From: Samuel Gordalina Date: Fri, 28 Jul 2023 11:20:33 -1000 Subject: [PATCH] Write file to temp dir to ensure it is writable Fixes #230 --- src/CacheTool.php | 17 ++++++++++++++++- tests/CacheToolTest.php | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/CacheTool.php b/src/CacheTool.php index f6f6333..4789329 100644 --- a/src/CacheTool.php +++ b/src/CacheTool.php @@ -235,7 +235,7 @@ protected function getWritableTempDir($tempDir = null) { if (is_null($tempDir)) { $tempDirs = ['/dev/shm', '/var/run', sys_get_temp_dir()]; foreach ($tempDirs as $dir) { - if (is_dir($dir) && is_writable($dir)) { + if ($this->isWritable($dir)) { $tempDir = $dir; break; } @@ -248,4 +248,19 @@ protected function getWritableTempDir($tempDir = null) { return $tempDir; } + + protected function isWritable($tempDir) { + if (!is_dir($tempDir) || !is_writable($tempDir)) { + return false; + } + + $tempFile = tempnam($tempDir, 'cachetool-test'); + + if ($tempFile === false) { + return false; + } + + @unlink($tempFile); + return true; + } } diff --git a/tests/CacheToolTest.php b/tests/CacheToolTest.php index c2106c1..579eeb3 100644 --- a/tests/CacheToolTest.php +++ b/tests/CacheToolTest.php @@ -74,6 +74,11 @@ public function testWithInexistentTempDir() { rmdir($dir); } + public function testWithExistentTempDir() { + $cachetool = new CacheTool(null); + $this->assertDirectoryExists($cachetool->getTempDir()); + } + public function testWithSetAdapterAndLogger() { $logger = $this->getLogger();