[Filesystem] Better error handling in remove()

This commit is contained in:
Nicolas Grekas 2016-04-12 10:59:55 +02:00
parent 302e1928b8
commit b848ddb7f0
1 changed files with 12 additions and 9 deletions

View File

@ -140,24 +140,27 @@ class Filesystem
*/
public function remove($files)
{
$files = iterator_to_array($this->toIterator($files));
if ($files instanceof \Traversable) {
$files = iterator_to_array($files, false);
} elseif (!is_array($files)) {
$files = array($files);
}
$files = array_reverse($files);
foreach ($files as $file) {
if (@(unlink($file) || rmdir($file))) {
continue;
}
if (is_link($file)) {
// See https://bugs.php.net/52176
$error = error_get_last();
throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {
$error = error_get_last();
throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
}
} elseif (is_dir($file)) {
$this->remove(new \FilesystemIterator($file));
$this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
if (!@rmdir($file)) {
if (!@rmdir($file) && file_exists($file)) {
$error = error_get_last();
throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message']));
}
} elseif (file_exists($file)) {
} elseif (!@unlink($file) && file_exists($file)) {
$error = error_get_last();
throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, $error['message']));
}