Provides an infrastructure to streamline automatic file cleanup when Doctrine entities are deleted. The bundle abstracts the file management logic through a registry pattern, allowing applications to implement type-specific file managers while maintaining a clean separation of concerns.
composer require mikamatto/file-cleanup-bundleuse Mikamatto\FileCleanupBundle\Contracts\FileBoundInterface;
class Video implements FileBoundInterface
{
public function getHandledFileTypes(): array
{
return ['image']; // Types of files this entity handles
}
public function getBoundFilesByType(string $type): array
{
if ($type !== 'image') {
return [];
}
$files = [];
if ($this->preview) {
$files[] = [
'path' => $this->preview,
'type' => 'preview'
];
}
if ($this->thumbnail) {
$files[] = [
'path' => $this->thumbnail,
'type' => 'thumb'
];
}
return $files;
}
public function getFileOwnerId(): int
{
return $this->id;
}
}use Mikamatto\FileCleanupBundle\Contracts\FileManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
#[AutoconfigureTag('mikamatto_file_cleanup.manager')]
class ImageManager implements FileManagerInterface
{
public function getHandledType(): string
{
return 'image';
}
public function deleteFiles(array $files, int $ownerId): void
{
foreach ($files as $file) {
// Each file has 'path' and 'type'
$this->deleteFile($file['path'], $ownerId, $file['type']);
}
}
}- When an entity implementing
FileBoundInterfaceis deleted:- The bundle's event subscriber is triggered
- It gets the file types from
getHandledFileTypes() - For each type, it finds the appropriate manager via
getHandledType() - Gets the files to delete via
getBoundFilesByType() - Passes the files to the manager's
deleteFiles()method
The format of the files array returned by getBoundFilesByType() should match what your FileManager implementation expects. The bundle itself doesn't impose any specific structure. For example:
return [
'preview' => [
'path' => 'path/to/preview.jpg',
'type' => 'preview'
],
'thumb' => [
'path' => 'path/to/thumb.jpg',
'type' => 'thumb'
]
];- PHP 8.2 or higher
- Symfony 6.4 or higher
MIT