Skip to content

Commit b992b1b

Browse files
fix: improve recursive delete to handle hidden files (#152)
1 parent 32b6259 commit b992b1b

2 files changed

Lines changed: 29 additions & 5 deletions

File tree

src/Storage/Device/Local.php

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -338,14 +338,26 @@ public function move(string $source, string $target): bool
338338
public function delete(string $path, bool $recursive = false): bool
339339
{
340340
if (\is_dir($path) && $recursive) {
341-
$files = $this->getFiles($path);
341+
$entries = \scandir($path);
342342

343-
foreach ($files as $file) {
344-
$this->delete($file, true);
343+
if ($entries === false) {
344+
return false;
345345
}
346346

347-
\rmdir($path);
348-
} elseif (\is_file($path) || \is_link($path)) {
347+
foreach ($entries as $entry) {
348+
if ($entry === '.' || $entry === '..') {
349+
continue;
350+
}
351+
352+
if (! $this->delete($path.DIRECTORY_SEPARATOR.$entry, true)) {
353+
return false;
354+
}
355+
}
356+
357+
return \rmdir($path);
358+
}
359+
360+
if (\is_file($path) || \is_link($path)) {
349361
return \unlink($path);
350362
}
351363

tests/Storage/Device/LocalTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,18 @@ public function testDelete()
107107
$this->assertEquals(is_readable($this->object->getPath('text-for-delete.txt')), false);
108108
}
109109

110+
public function testRecursiveDeleteRemovesHiddenFiles()
111+
{
112+
$directory = $this->object->getPath('delete-hidden');
113+
114+
$this->assertTrue($this->object->createDirectory($directory));
115+
$this->assertTrue($this->object->write($directory.DIRECTORY_SEPARATOR.'.hidden', 'secret'));
116+
$this->assertTrue($this->object->write($directory.DIRECTORY_SEPARATOR.'visible', 'visible'));
117+
118+
$this->assertTrue($this->object->delete($directory, true));
119+
$this->assertFalse($this->object->exists($directory));
120+
}
121+
110122
public function testFileSize()
111123
{
112124
$this->assertEquals($this->object->getFileSize(__DIR__.'/../../resources/disk-a/kitten-1.jpg'), 599639);

0 commit comments

Comments
 (0)