From d4b86b0e955ff128288bc676f293a5f05059cfff Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 5 Jan 2024 15:30:32 +0000 Subject: [PATCH] [core] redo deltree to also delete dotfiles, fixes #972 --- core/polyfills.php | 40 +++++++----------------------------- core/tests/PolyfillsTest.php | 16 +++++++++++++++ 2 files changed, 23 insertions(+), 33 deletions(-) diff --git a/core/polyfills.php b/core/polyfills.php index 0e6f6afd..7e086e25 100644 --- a/core/polyfills.php +++ b/core/polyfills.php @@ -54,42 +54,16 @@ function ip_in_range(string $IP, string $CIDR): bool /** * Delete an entire file heirachy - * - * from a patch by Christian Walde; only intended for use in the - * "extension manager" extension, but it seems to fit better here */ -function deltree(string $f): void +function deltree(string $dir): void { - //Because Windows (I know, bad excuse) - if (PHP_OS === 'WINNT') { - $real = realpath($f); - $path = realpath('./').'\\'.str_replace('/', '\\', $f); - if ($path != $real) { - rmdir($path); - } else { - foreach (glob($f.'/*') as $sf) { - if (is_dir($sf) && !is_link($sf)) { - deltree($sf); - } else { - unlink($sf); - } - } - rmdir($f); - } - } else { - if (is_link($f)) { - unlink($f); - } elseif (is_dir($f)) { - foreach (glob($f.'/*') as $sf) { - if (is_dir($sf) && !is_link($sf)) { - deltree($sf); - } else { - unlink($sf); - } - } - rmdir($f); - } + $di = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::KEY_AS_PATHNAME); + $ri = new \RecursiveIteratorIterator($di, \RecursiveIteratorIterator::CHILD_FIRST); + /** @var \SplFileInfo $file */ + foreach ($ri as $filename => $file) { + $file->isDir() ? rmdir($filename) : unlink($filename); } + rmdir($dir); } /** diff --git a/core/tests/PolyfillsTest.php b/core/tests/PolyfillsTest.php index f8e023f0..14c4b111 100644 --- a/core/tests/PolyfillsTest.php +++ b/core/tests/PolyfillsTest.php @@ -235,4 +235,20 @@ class PolyfillsTest extends TestCase // A single IP should be interpreted as a /32 $this->assertTrue(ip_in_range("1.2.3.4", "1.2.3.4")); } + + public function test_deltree() + { + $tmp = sys_get_temp_dir(); + $dir = "$tmp/test_deltree"; + mkdir($dir); + file_put_contents("$dir/foo", "bar"); + mkdir("$dir/baz"); + file_put_contents("$dir/baz/.qux", "quux"); + $this->assertTrue(file_exists($dir)); + $this->assertTrue(file_exists("$dir/foo")); + $this->assertTrue(file_exists("$dir/baz")); + $this->assertTrue(file_exists("$dir/baz/.qux")); + deltree($dir); + $this->assertFalse(file_exists($dir)); + } }