Merge pull request #2 from biondizzle/codex/find-and-fix-important-bug

Fix bucket cleanup
This commit is contained in:
biondizzle
2025-06-05 09:44:13 -04:00
committed by GitHub

View File

@@ -79,10 +79,10 @@ class S3Service
$this->entityManager->remove($bucket);
$this->entityManager->flush();
// Remove bucket directory if empty
// Remove bucket directory and any leftover sub directories
$bucketPath = $this->storageBasePath . '/' . $bucket->getName();
if (is_dir($bucketPath) && count(scandir($bucketPath)) === 2) { // Only . and ..
rmdir($bucketPath);
if (is_dir($bucketPath)) {
$this->removeDirectoryRecursively($bucketPath);
}
return true;
@@ -158,6 +158,8 @@ class S3Service
// Delete file
if (file_exists($fullPath)) {
unlink($fullPath);
// Clean up empty directories created for the object
$this->removeEmptyParentDirectories(dirname($fullPath), $this->storageBasePath . '/' . $object->getBucket()->getName());
}
// Remove database record
@@ -427,4 +429,41 @@ class S3Service
// Simplified signature calculation - implement full AWS Signature V4 here
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);
}
}