From 39ce053fbb018b6afcb2d6aaffdb0df61a616832 Mon Sep 17 00:00:00 2001 From: kenjis Date: Wed, 22 Dec 2021 09:08:13 +0900 Subject: [PATCH] fix: directory_mirror() throws an error if destination directory exists Fixes #5478 --- system/Helpers/filesystem_helper.php | 4 ++- tests/system/Helpers/FilesystemHelperTest.php | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/system/Helpers/filesystem_helper.php b/system/Helpers/filesystem_helper.php index 52341b848e06..89d4d507f961 100644 --- a/system/Helpers/filesystem_helper.php +++ b/system/Helpers/filesystem_helper.php @@ -91,7 +91,9 @@ function directory_mirror(string $originDir, string $targetDir, bool $overwrite $target = $targetDir . substr($origin, $dirLen); if ($file->isDir()) { - mkdir($target, 0755); + if (! is_dir($target)) { + mkdir($target, 0755); + } } elseif (! is_file($target) || ($overwrite && is_file($target))) { copy($origin, $target); } diff --git a/tests/system/Helpers/FilesystemHelperTest.php b/tests/system/Helpers/FilesystemHelperTest.php index c48ccd1ff328..7b837064a410 100644 --- a/tests/system/Helpers/FilesystemHelperTest.php +++ b/tests/system/Helpers/FilesystemHelperTest.php @@ -14,6 +14,7 @@ use CodeIgniter\Test\CIUnitTestCase; use InvalidArgumentException; use org\bovigo\vfs\vfsStream; +use org\bovigo\vfs\visitor\vfsStreamStructureVisitor; /** * @internal @@ -161,6 +162,34 @@ public function testDirectoryMirrorNotOverwrites() $this->assertSame($this->structure['boo']['faz'], $result); } + public function testDirectoryMirrorSkipExistingFolder() + { + $this->assertTrue(function_exists('directory_mirror')); + + $this->structure = [ + 'src' => [ + 'AnEmptyFolder' => [], + ], + 'dest' => [ + 'AnEmptyFolder' => [], + ], + ]; + vfsStream::setup('root', null, $this->structure); + $root = rtrim(vfsStream::url('root') . DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + + // skips the existing folder + directory_mirror($root . 'src', $root . 'dest'); + + $structure = vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure(); + $this->assertSame([], $structure['root']['dest']['AnEmptyFolder']); + + // skips the existing folder (the same as overwrite = true) + directory_mirror($root . 'src', $root . 'dest', false); + + $structure = vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure(); + $this->assertSame([], $structure['root']['dest']['AnEmptyFolder']); + } + public function testWriteFileSuccess() { $vfs = vfsStream::setup('root');