Skip to content

Latest commit

Β 

History

345 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FileManagerSystem (v1.0.60)

FileManagerSystem is a Symfony bundle that provides easy and intuitive management of files and directories: creation, deletion, moving, MIME type handling, image resizing, and more.

It is designed to simplify file management within any Symfony application.

⚠️ State Management

This bundle is stateful: it maintains a navigation context (defaultDirectory, relativeDirectory) across operations.

In the V2 modular architecture, this state is centralized in PathManager and shared across all 6 specialized managers within a single FileManagerService instance (so calling setDefaultDirectory() immediately propagates to file, directory, image, and archive operations).

Note

  • Standard PHP-FPM: shared: false on FileManagerService (with a shared PathManager per request) ensures clean state isolation.
  • Worker runtimes (FrankenPHP / Swoole): implement Symfony\Contracts\Service\ResetInterface on PathManager to reset paths between requests.

πŸ—οΈ Architecture (V2 β€” Modular Managers)

To keep the codebase maintainable and adhere to the Single Responsibility Principle (SRP), the bundle follows a Facade pattern (FileManagerService / _FileManagerService) delegating to 6 specialized managers located in src/Service/Manager/:

Manager Responsibility
PathManager Holds current working directories (kernelDirectory, defaultDirectory, relativeDirectory) and resolves/validates paths.
MimeManager Centralizes EXTENSIONS / MIME_TYPES mappings and guesses real file MIME types on disk.
FileManager Local/remote file reading, file creation, uploads, listing (getFiles), copy, move, rename, delete, and slug generation.
DirectoryManager Directory creation (+, /), listing (getDirs), recursive tree (getDirsTree), Symfony ChoiceType flattening (buildDirectoriesMap), and empty folder cleanup (cleanDir).
ImageManager Image dimensions, GD resizing (JPEG/PNG/WEBP), file size calculation (getSize), and human-readable formatting (getSizeName).
ArchiveManager Single file or bulk downloads (download, downloadBulk) with automatic temporary ZIP creation and post-send cleanup.

Dependency graph (strictly acyclic β€” zero circular dependencies):

FileManagerService (Facade)
 β”œβ”€β”€ PathManager        (core state β€” no internal dependencies)
 β”œβ”€β”€ MimeManager        ──► PathManager
 β”œβ”€β”€ ArchiveManager     ──► PathManager
 β”œβ”€β”€ ImageManager       ──► PathManager, MimeManager
 β”œβ”€β”€ FileManager        ──► PathManager, MimeManager, ImageManager
 └── DirectoryManager   ──► PathManager, FileManager, ImageManager

Tip

Switching to V2: src/Service/_FileManagerService.php exposes 100% of the existing public API (identical method names, parameter names, and return types). To activate it, replace src/Service/FileManagerService.php with _FileManagerService.php (renaming the class to FileManagerService) and enable the ## V2 block in config/services.yaml.


πŸš€ Installation

Install the bundle via Composer:

composer require anfallnorr/file-manager-system

βš™οΈ Configuration

1. Register the Bundle

Add the bundle to your config/bundles.php file:

return [
    // ...
    Anfallnorr\FileManagerSystem\FileManagerSystem::class => ['all' => true],
];

2. AssetMapper Configuration (Optional)

Warning

If you want to use the built-in controller and assets provided by the bundle, create the following configuration files.

Create config/packages/file_manager_system.yaml:

framework:
    asset_mapper:
        paths:
            - '%kernel.project_dir%/vendor/anfallnorr/file-manager-system/assets'

Create config/routes/file_manager_system.yaml:

file_manager_system:
    resource: '../../vendor/anfallnorr/file-manager-system/src/Controller/'
    type: attribute
    prefix: /files-manager 

πŸ’‘ Usage

Service Injection

Inject the FileManagerService into your controller or service:

public function __construct(
    private FileManagerService $fmService
) {
    $this->fmService->setDefaultDirectory(directory: '/var/uploads');
}

For convenience in examples below:

$fmService = $this->fmService;

πŸ“‚ 1. Directory Management

πŸ“Œ Get the Default Upload Directory

$defaultDirectory = $fmService->getDefaultDirectory();
// Returns: /path/to/project/public/uploads

πŸ“Œ Get the Relative Upload Directory

$relativeDirectory = $fmService->getRelativeDirectory();
// Returns: /uploads

πŸ“Œ Set a New Default Upload Directory

$directory = $fmService
    ->setDefaultDirectory(directory: '/var/uploads')
    ->getDefaultDirectory();
// Returns: /path/to/project/var/uploads

πŸ“ 1.1. Listing Directories

getDirs(string $path = '/', string $excludeDir = '', string|array|null $depth = '== 0'): array
Explore the file system with support for exclusions, depth control, and relative paths.

$dirs = $fmService->getDirs(path: 'uploads', depth: '== 1');

getDirsTree(string $path = '/', string $excludeDir = ""): array
Retrieve directories in a recursive tree structure, including sub-folders and files metadata.

$tree = $fmService->getDirsTree(path: 'uploads');

buildDirectoriesMap(array $directories, int $depth = 1, bool $buildDirectoryChoices = false): array
Flatten a recursive directory tree (from getDirsTree()) and optionally build an indented array ready for Symfony ChoiceType.

$result = $fmService->buildDirectoriesMap(directories: $tree, buildDirectoryChoices: true);
$choices = $result['choicesBuilder'];

hasDir(): bool
Check if the default directory contains at least one sub-directory.

if ($fmService->hasDir()) {
    // Contains sub-directories
}

πŸ“ 1.2. Creating and Cleaning Directories

createDir(?string $directory = null, bool $returnDetails = false): array|bool
Create a new directory within the default directory (slugified automatically), or initialize the default directory when null. Supports nested (folder/sub) and multiple (folder1+folder2) creations.

$fmService->createDir(directory: 'Hello World!'); // Creates: hello-world

cleanDir(?string $dir = null): void
Recursively clean a directory by removing empty folders.

$fmService->cleanDir(dir: 'uploads/temp');

πŸ“„ 2. File Management

πŸ“„ 2.1. Listing and Reading Files

getFiles(string $path = '/', string|array|null $depth = '== 0', ?string $folder = null, string|array|null $ext = null): array
Offers complete control over file search: depth, extension, folder filtering.

$files = $fmService->getFiles(path: 'uploads', ext: 'jpg');

getFileContent(string $relativeFile): string
Read and return the entire content of a file.

$content = $fmService->getFileContent(relativeFile: 'storage/data.json');

getRemoteFileContent(string $url): string
Fetch content from a remote URL.

$content = $fmService->getRemoteFileContent(url: 'https://example.com/data.json');

πŸ“„ 2.2. Creating and Uploading Files

createFile(string $filename, string $content = '...'): void
Create a new file with optional content.

$fmService->createFile(filename: 'welcome.html', content: '<h1>Hello</h1>');

upload(UploadedFile|File|array $files, string $folder, string $newName = '', bool $returnDetails = false): array|bool
Upload files, handle slugification, and generate useful metadata.

$uploaded = $fmService->upload(files: $file, folder: '/var/www/uploads', newName: 'my-file', returnDetails: true);

πŸ”„ 3. File & Directory Operations

exists(?string $filePath = null): bool
Check if a file or directory physically exists.

if ($fmService->exists(filePath: 'images/photo.jpg')) {
    // File exists
}

copy(string $source, string $destination, bool $override = false): bool
Duplicate a file or directory.

$fmService->copy(source: 'uploads/file.txt', destination: 'backup/file.txt', override: true);

move(string $origine, string $target, bool $overwrite = false): bool
Move a file or directory to a new location.

$fmService->move(origine: '/uploads/temp/image.jpg', target: '/uploads/final/image.jpg', overwrite: true);

rename(string $source, string $destination, bool $override = false): bool
Rename a file or directory (automatically slugifies the new name).

$fmService->rename(source: 'Photo Vacances.jpg', destination: 'nouvelle photo');
// Result: nouvelle-photo.jpg

remove(string $relativePath = ''): bool
Delete a file or a directory (and all its content).

$fmService->remove(relativePath: 'uploads/documents/file.txt'); // Delete specific file
$fmService->remove(); // Delete entire default directory

🎨 4. Media & Utilities

πŸ–ΌοΈ Image Handling

resizeImages(array $files, string $sourceDir, string $targetDir, int $width, int $quality = 100, ?string $suffix = null): array
Resize images while keeping aspect ratio and saving them to a new destination.

$fmService->resizeImages(files: ['img.jpg'], sourceDir: '/source', targetDir: '/target', width: 800, quality: 90, suffix: 'thumb');

getImageSize(string $filePath): ?array
Get the dimensions of an image (['width' => int, 'height' => int]).

$size = $fmService->getImageSize(filePath: 'uploads/photo.jpg');

πŸ“ Size & MIME

getSize(string|array $files, int $totalFileSize = 0): int|float
Calculate the total size in bytes of one or more files.

$bytes = $fmService->getSize(files: $filesArray);

getSizeName(int|float $size): string
Convert bytes into a human-readable format (Octets, Ko, Mo, Go).

$readable = $fmService->getSizeName(size: 10485760); // 10 Mo

getMimeTypes(): array
Get a complete list of supported MIME types.

$mimeTypes = $fmService->getMimeTypes();

getMimeType(string $key): string|array|null
Retrieve the MIME type for a given file extension.

$mimeType = $fmService->getMimeType(key: 'pdf');

getMimeContent(string $filename): ?string
Detect the real MIME type of a physical file based on its content.

$mimeContent = $fmService->getMimeContent(filename: 'uploads/photo.jpg');

⬇️ Download & Miscellaneous

download(string $name, ?string $directory = null): BinaryFileResponse
Force the download of a single file, or automatically compress and download a folder as a ZIP archive.

return $fmService->download(name: 'document.pdf');

downloadBulk(array $names, ?string $directory = null): BinaryFileResponse
Group multiple files into a ZIP archive and force its download.

return $fmService->downloadBulk(names: ['doc1.pdf', 'img.png']);

createSlug(string $string): string
Convert any string into a URL-safe slug.

$slug = $fmService->createSlug(string: 'Hello World !'); // hello-world

🎨 5. Optional: Twig Integration

If you are using Twig and want Bootstrap-styled forms, add the following to your Twig configuration.

Edit config/packages/twig.yaml:

twig:
    form_themes: ['bootstrap_5_layout.html.twig']

πŸ“š Additional Resources


πŸ“ License

This bundle is open-source and available under the MIT License.

Releases

Packages

Used by

Contributors

Languages