0

I currently have the function:

function deleteFileUsingID($fileID) {
    $this->service->files->delete($fileID);
}

How would I have to modify it such that after deleting the file, if no files exists within that folder, it deletes the folder itself.

itsMeMoriarty
  • 125
  • 1
  • 1
  • 9

1 Answers1

3

I believe your goal as follows.

  • When there are no files in the specific folder, you want to delete the folder.

In this case, you can check whether the files are in the folder using the method of "Files: list" in Drive API.

Modified script:

Please set the folder ID to $folderId = '###';.

function deleteFileUsingID($fileID) {
    $this->service->files->delete($fileID);

    $folderId = '###';  // Please set the folder ID.
    $fileList = $this->service->files->listFiles(array("q" => "'{$folderId}' in parents"));
    if (count($fileList->getFiles()) == 0) {
        $this->service->files->delete($folderId);
    }
}

Or, when you want to retrieve the folder ID from $fileID, you can also use the following script.

function deleteFileUsingID($fileID) {
    $folderIds = $this->service->files->get($fileID, array("fields" => "parents"))->getParents();

    $this->service->files->delete($fileID);

    if (count($folderIds) > 0) {
        $folderId = $folderIds[0];
        $fileList = $this->service->files->listFiles(array("q" => "'{$folderId}' in parents"));
        if (count($fileList->getFiles()) == 0) {
            $this->service->files->delete($folderId);
        }
    }
}
  • In this modified script, after $this->service->files->delete($fileID); was run, it checks whether the files are in the folder using the method of "Files: list". When no files in the folder, the folder is deleted.

Note:

  • In this case, the folder is deleted. So please be careful this. I would like to recommend to use the sample folder for testing the script.

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • 2
    you can make a get method to get the parent id for that file befor $this->service->files->delete($fileID);, to avoid add the folder ID manually – GNassro Aug 17 '20 at 03:07
  • 2
    @GNassro Thank you for your comment. I can understand about your proposal. From OP's question, I thought that OP might have already had the folder ID. If OP wants it, I would like to add it. Thank you. – Tanaike Aug 17 '20 at 03:23
  • 1
    @GNassro Now, I added your proposal in the answer, because I thought that it will be also useful for other users when that is added. Could you please confirm it? In the case of the additional script, the folder ID is retrieved by `$fileID`. – Tanaike Aug 17 '20 at 03:50