diff --git a/src/TemporaryDirectory.php b/src/TemporaryDirectory.php index 137b21a..4464834 100644 --- a/src/TemporaryDirectory.php +++ b/src/TemporaryDirectory.php @@ -15,6 +15,8 @@ class TemporaryDirectory protected bool $forceCreate = false; + protected bool $deleteWhenDestroyed = false; + public function __construct(string $location = '') { $this->location = $this->sanitizePath($location); @@ -182,4 +184,18 @@ protected function deleteDirectory(string $path): bool return false; } } + + public function deleteWhenDestroyed(bool $deleteWhenDestroyed = true): self + { + $this->deleteWhenDestroyed = $deleteWhenDestroyed; + + return $this; + } + + public function __destruct() + { + if ($this->deleteWhenDestroyed) { + $this->delete(); + } + } } diff --git a/tests/TemporaryDirectoryTest.php b/tests/TemporaryDirectoryTest.php index 26fbdbb..88035fb 100644 --- a/tests/TemporaryDirectoryTest.php +++ b/tests/TemporaryDirectoryTest.php @@ -293,6 +293,22 @@ public function it_exists_function_should_tell_if_directory_exists() $this->assertTrue($temporaryDirectory->exists()); } + /** @test */ + public function it_can_delete_when_object_is_destroyed() + { + $temporaryDirectory = (new TemporaryDirectory()) + ->name($this->temporaryDirectory) + ->deleteWhenDestroyed() + ->create(); + + $fullPath = $temporaryDirectory->path(); + + $this->assertDirectoryExists($fullPath); + + unset($temporaryDirectory); + $this->assertDirectoryDoesNotExist($fullPath); + } + protected function deleteDirectory(string $path): bool { if (is_link($path)) {