fix cleanup of bucket directories
This commit is contained in:
@@ -79,10 +79,10 @@ class S3Service
|
|||||||
$this->entityManager->remove($bucket);
|
$this->entityManager->remove($bucket);
|
||||||
$this->entityManager->flush();
|
$this->entityManager->flush();
|
||||||
|
|
||||||
// Remove bucket directory if empty
|
// Remove bucket directory and any leftover sub directories
|
||||||
$bucketPath = $this->storageBasePath . '/' . $bucket->getName();
|
$bucketPath = $this->storageBasePath . '/' . $bucket->getName();
|
||||||
if (is_dir($bucketPath) && count(scandir($bucketPath)) === 2) { // Only . and ..
|
if (is_dir($bucketPath)) {
|
||||||
rmdir($bucketPath);
|
$this->removeDirectoryRecursively($bucketPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -158,6 +158,8 @@ class S3Service
|
|||||||
// Delete file
|
// Delete file
|
||||||
if (file_exists($fullPath)) {
|
if (file_exists($fullPath)) {
|
||||||
unlink($fullPath);
|
unlink($fullPath);
|
||||||
|
// Clean up empty directories created for the object
|
||||||
|
$this->removeEmptyParentDirectories(dirname($fullPath), $this->storageBasePath . '/' . $object->getBucket()->getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove database record
|
// Remove database record
|
||||||
@@ -427,4 +429,41 @@ class S3Service
|
|||||||
// Simplified signature calculation - implement full AWS Signature V4 here
|
// Simplified signature calculation - implement full AWS Signature V4 here
|
||||||
return hash_hmac('sha256', $bucketName . $objectKey . serialize($params), $secretKey);
|
return hash_hmac('sha256', $bucketName . $objectKey . serialize($params), $secretKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recursively remove empty parent directories up to a given path.
|
||||||
|
*/
|
||||||
|
private function removeEmptyParentDirectories(string $path, string $stopAt): void
|
||||||
|
{
|
||||||
|
while (str_starts_with($path, $stopAt) && $path !== $stopAt) {
|
||||||
|
if (!is_dir($path) || count(scandir($path)) > 2) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
rmdir($path);
|
||||||
|
$path = dirname($path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a directory and all of its content.
|
||||||
|
*/
|
||||||
|
private function removeDirectoryRecursively(string $dir): void
|
||||||
|
{
|
||||||
|
if (!is_dir($dir)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$items = array_diff(scandir($dir), ['.', '..']);
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$path = $dir . '/' . $item;
|
||||||
|
if (is_dir($path)) {
|
||||||
|
$this->removeDirectoryRecursively($path);
|
||||||
|
} else {
|
||||||
|
unlink($path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rmdir($dir);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user