已经 4 年了,他们仍然没有为此提供适当的 API。
对于仍然需要解决方法的您,这里有一个选项。
此示例是删除父文件夹、其嵌套文件夹及其所有内容。
<?php
/**
* Delete nested folders for Google Cloud Storage
*/
class ClassName {
/** @var Google_Service_Storage $storageService */
public $storageService;
/** @var string $bucket */
public $bucket = '';
/**
* Remove an object
*
* @param string $objectPath
* @return boolean
*/
public function removeObject($objectPath) {
// validator
try {
if (!$this->storageService->objects->get($this->bucket, $objectPath)) {
// log error
return false;
}
} catch (Exception $ex) {
// leave this empty
}
// remove action
try {
$this->storageService->objects->delete($this->bucket, $objectPath);
} catch (Exception $ex) {
// log error
return false;
}
// log success
return true;
}
/**
* Remove the specified container
*
* @param string $path
* @return boolean
*/
public function removeContainer($path) {
$c = array();
$c['delimiter'] = '/';
if (!empty($path) && $path != '/') {
$c['prefix'] = $path;
}
$objects = null;
// validator
try {
$objects = $this->storageService->objects->listObjects($this->bucket, $c);
if (empty($objects)) {
if (!$this->storageService->objects->get($this->bucket, $path)) {
// log error
return false;
}
}
} catch (Exception $ex) {
// leave this empty
}
// remove action
try {
if (empty($objects)) {
$this->storageService->objects->delete($this->bucket, $path);
} else {
/**
* Process files first
*/
$files = $objects->getItems();
if (!empty($files)) {
foreach ($files as $file) {
$this->removeObject($file->getName());
}
}
/**
* And folders later
*/
$folders = $objects->getPrefixes();
if (!empty($folders)) {
foreach ($folders as $folder) {
$this->removeContainer($folder);
}
}
}
} catch (Exception $ex) {
// log error
return false;
}
// log success
return true;
}
}
这是它在数据库中的登录方式,以解释递归过程。
如果您好奇为什么空文件夹s 在日志中出现两次file_remove
and directory_remove
,这$objects = $this->driver->objects->listObjects($this->bucket, $c);
部分将文件夹的名称重新列出到$files = $objects->getItems();
,
可能是因为它不是物理文件夹,而是表示为文件夹的空文件。