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

php-standard-library/filesystem

Type-safe filesystem utilities for PHP Standard Library. Perform common file and directory operations with consistent APIs and proper exception handling, improving safety and clarity over raw PHP functions. Documentation and contribution links included.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/filesystem
    

    Add the service provider to config/app.php (if using Laravel):

    'providers' => [
        // ...
        PhpStandardLibrary\Filesystem\FilesystemServiceProvider::class,
    ],
    

    Publish config (if available):

    php artisan vendor:publish --provider="PhpStandardLibrary\Filesystem\FilesystemServiceProvider"
    
  2. First Use Case Resolve and normalize paths in a Laravel controller:

    use PhpStandardLibrary\Filesystem\Facades\Filesystem;
    
    $resolvedPath = Filesystem::path()->resolve('/var/www/storage', 'logs/app.log');
    $normalizedPath = Filesystem::path()->normalize($resolvedPath);
    

Where to Look First

  • Facade: PhpStandardLibrary\Filesystem\Facades\Filesystem (for quick access).
  • Core Classes:
    • PhpStandardLibrary\Filesystem\Path (path manipulation).
    • PhpStandardLibrary\Filesystem\File (file operations).
    • PhpStandardLibrary\Filesystem\Directory (directory operations).
  • Documentation: Check vendor/php-standard-library/filesystem/README.md for API reference.

Implementation Patterns

Common Workflows

1. Path Handling

  • Joining paths (cross-platform safe):
    $path = Filesystem::path()->join('storage', 'logs', 'app.log');
    
  • Resolving relative paths:
    $absolutePath = Filesystem::path()->resolve(base_path(), 'app/Config.php');
    

2. File Operations

  • Reading/Writing Files:
    // Write
    Filesystem::file()->put($path, 'Hello, world!');
    
    // Read
    $content = Filesystem::file()->get($path);
    
  • Copy/Move with error handling:
    try {
        Filesystem::file()->copy($source, $destination);
    } catch (\PhpStandardLibrary\Filesystem\Exceptions\FileOperationException $e) {
        Log::error($e->getMessage());
    }
    

3. Directory Management

  • Ensure directory exists:
    Filesystem::directory()->ensure($path);
    
  • List files recursively:
    $files = Filesystem::directory()->files($directory, true);
    

4. Metadata Inspection

  • Check file existence and type:
    if (Filesystem::file()->exists($path) && Filesystem::file()->isReadable($path)) {
        $size = Filesystem::file()->size($path);
    }
    

5. Laravel Integration

  • Replace Storage facade for custom logic:
    // Instead of:
    Storage::put('file.txt', 'content');
    
    // Use:
    Filesystem::file()->put(storage_path('app/file.txt'), 'content');
    
  • Custom filesystem driver (extend FilesystemManager):
    // config/filesystems.php
    'disks' => [
        'custom' => [
            'driver' => 'php-standard-library',
            'root'   => storage_path('app'),
        ],
    ],
    

Best Practices

  • Use ensure() for directories before writing files to avoid race conditions.
  • Leverage exceptions for error handling (e.g., FileNotFoundException, PermissionDeniedException).
  • Prefer Path methods over raw DIRECTORY_SEPARATOR for cross-platform compatibility.
  • Cache resolved paths if used frequently (e.g., in a service container).

Gotchas and Tips

Pitfalls

  1. Path Resolution Quirks

    • resolve() uses the current working directory as the base if no absolute path is provided.
      // Avoid:
      $path = Filesystem::path()->resolve('relative/path'); // May fail if CWD is unexpected.
      
      // Prefer:
      $path = Filesystem::path()->resolve(base_path(), 'relative/path');
      
    • Trailing slashes in paths may cause issues with join() or resolve(). Use normalize() to clean them:
      $cleanPath = Filesystem::path()->normalize('/path/with/trailing//slashes/');
      
  2. Permission Handling

    • The package does not auto-create parent directories when writing files. Use ensure() on the parent:
      $parent = dirname($path);
      Filesystem::directory()->ensure($parent);
      Filesystem::file()->put($path, 'content');
      
    • Symlink behavior: The package follows symlinks by default. Use isSymlink() to check or disable following with resolve(..., false).
  3. Edge Cases in File Operations

    • Large files: Use file()->append() or file()->writeStream() for memory efficiency.
    • Binary files: Ensure proper encoding when reading/writing (e.g., file()->get($path, 'binary')).
  4. Laravel-Specific Issues

    • Caching: If using the package in a Laravel command, resolved paths may change between runs if base_path() or storage_path() are dynamic.
    • Testing: Mock the Filesystem facade in tests to avoid filesystem I/O:
      $this->mock(Filesystem::class)->shouldReceive('file')->andReturnSelf()
          ->shouldReceive('exists')->andReturn(true);
      

Debugging Tips

  1. Enable Verbose Errors Set the debug config option to true to get detailed exceptions:

    // config/filesystem.php
    'debug' => env('FILESYSTEM_DEBUG', false),
    
  2. Log Path Operations Wrap path resolutions in logs for debugging:

    $path = Filesystem::path()->resolve($base, $relative);
    Log::debug('Resolved path', ['path' => $path, 'base' => $base, 'relative' => $relative]);
    
  3. Check File Permissions Use file()->isWritable() or directory()->isWritable() to diagnose permission issues:

    if (!Filesystem::file()->isWritable($path)) {
        throw new \RuntimeException("Cannot write to {$path}. Check permissions.");
    }
    

Extension Points

  1. Custom Path Resolver Extend PhpStandardLibrary\Filesystem\Path to add domain-specific logic:

    class CustomPath extends \PhpStandardLibrary\Filesystem\Path
    {
        public function resolveWithBase(string $base, string $path): string
        {
            return parent::resolve($this->normalize($base), $path);
        }
    }
    
  2. Filesystem Events Listen for file/directory operations via Laravel events (if the package supports them):

    // Example (hypothetical)
    Filesystem::file()->listen(function ($event) {
        Log::info("File event: {$event->type}", ['path' => $event->path]);
    });
    
  3. Override Default Behavior Bind your own implementations to the container:

    $app->bind(\PhpStandardLibrary\Filesystem\Contracts\File::class, function ($app) {
        return new CustomFile();
    });
    

Performance Considerations

  • Avoid redundant exists() checks: The package optimizes these internally, but chaining them (e.g., if (exists() && isReadable())) may still hit the filesystem twice.
  • Batch operations: Use directory()->files() with true for recursion, but limit depth if performance is critical:
    $files = Filesystem::directory()->files($dir, true, 2); // Max depth = 2
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport