Recursively delete directories Gau Frette FTP adapter


To with FTP recursively delete files and directories adapter Gau Frette, you can apply following trick to avoid the error message:

ftp_rmdir(): Directory not empty.

1. just delete all files

2. then delete the lowest directories up to the top:

/**
 * @param Filesystem $fileSystem
 */
function deleteAllFilesInDirectory(Filesystem $fileSystem)
{
    // delete files first, than directories
    foreach ($fileSystem->keys() as $key) {
        if (!$fileSystem->isDirectory($key)) {
            $fileSystem->delete($key);
        }
    }
    $keys = $fileSystem->keys();
    usort($keys, function (string $a, string $b){
        $aCount = substr_count($a, '/');
        $bCount = substr_count($b, '/');
        return $bCount <=> $aCount;
    });
    foreach ($keys as $key) {
        $fileSystem->delete($key);
    }
}

Comments are closed.