Skip to content

Commit

Permalink
fix(temp-dir): allow to create a temporary directory for an existing …
Browse files Browse the repository at this point in the history
…dir path

+ throw an exception when user given dir path is not writeable
  • Loading branch information
kevin committed Aug 25, 2021
1 parent 4040468 commit 4995305
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Utils/Tempfile/TemporaryDirectory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

namespace Nekland\Utils\Tempfile;

use Nekland\Utils\Exception\LogicException;
use Nekland\Utils\Tempfile\Exception\ImpossibleToCreateDirectoryException;

class TemporaryDirectory
Expand All @@ -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) {
Expand Down
22 changes: 22 additions & 0 deletions tests/Nekland/Utils/Tempfile/TemporaryDirectoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 4995305

Please sign in to comment.