mikamatto / file-cleanup-bundle
Automatically cleans up files when their associated Doctrine entities are deleted
Installs: 8
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:symfony-bundle
Requires
- php: >=8.2
- doctrine/doctrine-bundle: ^2.11
- doctrine/orm: ^3.2
- symfony/dependency-injection: 7.*
- symfony/framework-bundle: 7.*
README
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.
Installation
composer require mikamatto/file-cleanup-bundle
Usage
1. Implement FileBoundInterface on your entity
use 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; } }
2. Create a FileManager service
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']); } } }
How it works
- When an entity implementing
FileBoundInterface
is 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' ] ];
Requirements
- PHP 8.2 or higher
- Symfony 6.4 or higher
License
MIT