From 499530585eace4c6885d2ebeb0d5f57fb90f1a8d Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Aug 2021 15:15:39 +0200 Subject: [PATCH] fix(temp-dir): allow to create a temporary directory for an existing dir path + throw an exception when user given dir path is not writeable --- src/Utils/Tempfile/TemporaryDirectory.php | 10 ++++++--- .../Utils/Tempfile/TemporaryDirectoryTest.php | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/Utils/Tempfile/TemporaryDirectory.php b/src/Utils/Tempfile/TemporaryDirectory.php index ebf64f4..c17086a 100644 --- a/src/Utils/Tempfile/TemporaryDirectory.php +++ b/src/Utils/Tempfile/TemporaryDirectory.php @@ -10,6 +10,7 @@ namespace Nekland\Utils\Tempfile; +use Nekland\Utils\Exception\LogicException; use Nekland\Utils\Tempfile\Exception\ImpossibleToCreateDirectoryException; class TemporaryDirectory @@ -24,18 +25,21 @@ class TemporaryDirectory private $removed; /** - * TemporaryDirectory constructor. - * * @param null|string $dir * @param string $prefix */ - public function __construct($dir = null, $prefix = 'phpgenerated') + public function __construct(string $dir = null, string $prefix = 'phpgenerated') { $this->removed = false; $this->wasAlreadyExisting = false; if (null !== $dir && \is_dir($dir)) { + if (!is_writable($dir)) { + throw new LogicException(\sprintf('The directory "%s" is not writeable.', $dir)); + } + $this->wasAlreadyExisting = true; $this->dir = $dir; + return; } if (null === $this->dir) { diff --git a/tests/Nekland/Utils/Tempfile/TemporaryDirectoryTest.php b/tests/Nekland/Utils/Tempfile/TemporaryDirectoryTest.php index 4f68c08..291d8ba 100644 --- a/tests/Nekland/Utils/Tempfile/TemporaryDirectoryTest.php +++ b/tests/Nekland/Utils/Tempfile/TemporaryDirectoryTest.php @@ -36,4 +36,26 @@ public function testItRemoveNonEmptyDirectoryIfIForceIt() $directory->remove(true); $this->assertTrue($directory->hasBeenRemoved()); } + + public function testCreateATempDirectoryAtAnExistingPathIsAllowed() + { + $directory = new TemporaryDirectory(); + $path = $directory->getPathname(); + new TemporaryDirectory($path); + + $this->assertDirectoryExists($path); + + $directory->remove(); + } + + public function testCreateTemporaryFileForNotWritableDirThrowException() + { + $path = sys_get_temp_dir() . '/testwritable' . uniqid('', true); + mkdir($path, 0444); + $this->assertDirectoryExists($path); + + $this->expectExceptionMessage("The directory \"$path\" is not writeable."); + new TemporaryDirectory($path); + unlink($path); + } }