Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filesystem Laravel Package

symfony/filesystem

Symfony Filesystem provides practical, cross-platform filesystem utilities for PHP: create/copy/move/remove files and directories, check existence, handle permissions, and more. Part of the Symfony Components with solid documentation and community support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/filesystem
    

    Add to composer.json under require:

    "symfony/filesystem": "^8.0"
    
  2. First Use Case: Use the Filesystem class for basic file/directory operations:

    use Symfony\Component\Filesystem\Filesystem;
    
    $fs = new Filesystem();
    
    // Create a directory
    $fs->mkdir('path/to/directory');
    
    // Copy a file
    $fs->copy('source.txt', 'destination.txt');
    
    // Remove a file
    $fs->remove('file.txt');
    
  3. Where to Look First:

    • Official Documentation
    • Symfony\Component\Filesystem\Filesystem class methods (e.g., mkdir, copy, remove, dumpFile, exists).
    • Symfony\Component\Filesystem\Path class for path manipulation (e.g., normalize, getFilename, isAbsolute).

Implementation Patterns

Core Workflows

1. File and Directory Management

  • Atomic Writes: Use dumpFile() to write files atomically, reducing race conditions:
    $fs->dumpFile('config.json', json_encode($config));
    
  • Recursive Operations: Use mirror() to replicate directory structures:
    $fs->mirror('source_dir', 'destination_dir');
    

2. Path Manipulation

  • Normalize Paths: Ensure cross-platform compatibility:
    $normalizedPath = Path::normalize('/path/with/../segments');
    
  • Relative Paths: Convert absolute paths to relative:
    $relativePath = Path::makePathRelative('/var/www/html', '/var/www/html/storage');
    

3. Permissions and Ownership

  • Set Permissions: Use chmod() for secure file access:
    $fs->chmod('file.txt', 0644);
    
  • Change Ownership: Use chown() (Linux/macOS only):
    $fs->chown('file.txt', 1000);
    

4. Temporary Files

  • Create and Clean Up Temp Files:
    $tempFile = tempnam(sys_get_temp_dir(), 'prefix');
    file_put_contents($tempFile, 'data');
    $fs->remove($tempFile); // Cleanup
    

5. Integration with Laravel

  • Service Provider Binding:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Filesystem::class, function () {
            return new Filesystem();
        });
    }
    
  • Artisan Commands:
    use Symfony\Component\Filesystem\Filesystem;
    
    class BackupCommand extends Command
    {
        protected $fs;
    
        public function __construct(Filesystem $fs)
        {
            parent::__construct();
            $this->fs = $fs;
        }
    
        public function handle()
        {
            $this->fs->mirror(storage_path('app'), backup_path('app'));
        }
    }
    

6. Handling Edge Cases

  • Check Existence Before Operations:
    if ($fs->exists('file.txt')) {
        $fs->remove('file.txt');
    }
    
  • Handle Errors Gracefully:
    try {
        $fs->remove('nonexistent_file.txt');
    } catch (\RuntimeException $e) {
        // Log or handle error
    }
    

Gotchas and Tips

Pitfalls

  1. Windows vs. UNIX Path Handling:

    • Issue: Path methods may incorrectly replace backslashes on UNIX systems (fixed in v8.0.9).
    • Fix: Always use Path::normalize() to ensure consistency:
      $path = Path::normalize('C:\Users\file.txt'); // Converts to forward slashes
      
  2. Permission Denied Errors:

    • Issue: Operations may fail silently or throw exceptions on restricted directories.
    • Fix: Use try-catch blocks and log errors:
      try {
          $fs->chmod('protected_file.txt', 0777);
      } catch (\RuntimeException $e) {
          Log::error('Permission denied: ' . $e->getMessage());
      }
      
  3. Temp File Cleanup on Windows:

    • Issue: Temp files may not delete properly on Windows (fixed in v7.1.5).
    • Fix: Use Filesystem::remove() explicitly:
      $fs->remove($tempFile);
      
  4. Atomic Writes and Race Conditions:

    • Issue: Concurrent writes to the same file can corrupt data.
    • Fix: Use dumpFile() for atomic writes:
      $fs->dumpFile('log.txt', $newContent, 0644);
      
  5. Path Injection Risks:

    • Issue: User-provided paths may lead to directory traversal attacks.
    • Fix: Validate paths using Path::isAbsolute() and sanitize inputs:
      if (!Path::isAbsolute($userInputPath)) {
          throw new \InvalidArgumentException('Invalid path');
      }
      

Debugging Tips

  1. Enable Verbose Output:

    • Use Filesystem::getDebug() to log operations:
      $fs->getDebug()->setVerbosity(Filesystem::VERBOSITY_DEBUG);
      
  2. Check Path Normalization:

    • Debug path issues with:
      $normalized = Path::normalize('/path/with/../segments');
      dd($normalized);
      
  3. Handle Windows-Specific Quirks:

    • Use str_replace('\\', '/', $path) as a fallback for legacy systems:
      $path = str_replace('\\', '/', $path);
      $normalized = Path::normalize($path);
      

Extension Points

  1. Custom Filesystem Adapter:

    • Extend Filesystem to add custom logic:
      class CustomFilesystem extends Filesystem
      {
          public function customOperation($path)
          {
              // Custom logic
          }
      }
      
  2. Event Listeners for File Operations:

    • Use Symfony’s FilesystemEvent (if available) or wrap operations in listeners:
      $fs->addListener('preRemove', function ($event) {
          // Log or validate before removal
      });
      
  3. Integration with Laravel Events:

    • Dispatch events for critical filesystem operations:
      event(new FilesystemOperationEvent('copy', ['source.txt', 'destination.txt']));
      

Configuration Quirks

  1. Disable Symlinks:

    • If working in restricted environments, disable symlink creation:
      $fs = new Filesystem();
      $fs->disableSymlinks();
      
  2. Custom Temp Directory:

    • Override the temp directory for testing:
      putenv('TMPDIR=' . storage_path('framework/tests'));
      
  3. Case-Insensitive Paths (Windows):

    • Normalize paths to avoid case-sensitivity issues:
      $normalized = Path::normalize(strtolower($path));
      

Performance Tips

  1. Batch Operations:

    • Use Filesystem::remove() with an array for multiple files:
      $fs->remove(['file1.txt', 'file2.txt']);
      
  2. Avoid Redundant Checks:

    • Cache existence checks if paths are static:
      if ($fs->exists($path)) {
          // Process file
      }
      
  3. Use mirror() for Large Directories:

    • Efficiently replicate directory structures:
      $fs->mirror('source_dir', 'destination_dir', null, ['override' => true]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle