mikamatto/file-cleanup-bundle

There is no license information available for the latest version (v1.0.0) of this package.

Automatically cleans up files when their associated Doctrine entities are deleted

v1.0.0 2025-05-06 20:41 UTC

This package is auto-updated.

Last update: 2025-06-06 21:01:18 UTC


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

  1. 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