Skip to content

Commit

Permalink
Merge pull request #17 from mcsky/fix/existent-temp-dir
Browse files Browse the repository at this point in the history
  • Loading branch information
Nek- authored Aug 25, 2021
2 parents 4040468 + 4995305 commit e94f808
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 e94f808

Please sign in to comment.