Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[Filesystem] remove dirs atomically if possible
  • Loading branch information
nicolas-grekas committed Feb 10, 2021
commit 17bccca9c6b0ce7756a7ea338f1ae5a7ea1d7de1
37 changes: 34 additions & 3 deletions src/Symfony/Component/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ public function remove($files)
} elseif (!\is_array($files)) {
$files = [$files];
}

self::doRemove($files, false);
}

private static function doRemove(array $files, bool $isRecursive): void
{
$files = array_reverse($files);
foreach ($files as $file) {
if (is_link($file)) {
Expand All @@ -170,10 +176,35 @@ public function remove($files)
throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError);
}
} elseif (is_dir($file)) {
$this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
if (!$isRecursive) {
$tmpName = \dirname(realpath($file)).'/.'.strrev(strtr(base64_encode(random_bytes(2)), '/=', '-.'));

if (file_exists($tmpName)) {
try {
self::doRemove([$tmpName], true);
} catch (IOException $e) {
}
}

if (!file_exists($tmpName) && self::box('rename', $file, $tmpName)) {
$origFile = $file;
$file = $tmpName;
} else {
$origFile = null;
}
}

$files = new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
self::doRemove(iterator_to_array($files, true), true);

if (!self::box('rmdir', $file) && file_exists($file) && !$isRecursive) {
$lastError = self::$lastError;

if (null !== $origFile && self::box('rename', $file, $origFile)) {
$file = $origFile;
}

if (!self::box('rmdir', $file) && file_exists($file)) {
throw new IOException(sprintf('Failed to remove directory "%s": ', $file).self::$lastError);
throw new IOException(sprintf('Failed to remove directory "%s": ', $file).$lastError);
}
} elseif (!self::box('unlink', $file) && (false !== strpos(self::$lastError, 'Permission denied') || file_exists($file))) {
throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError);
Expand Down