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

Finder Laravel Package

symfony/finder

Symfony Finder component provides a fluent API to locate and iterate files and directories. Filter by name, extension, size, date, contents, or path; search multiple locations; and traverse recursively with sorting and ignore rules for flexible filesystem searches.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/finder
    

    Laravel already includes this as a dependency (via symfony/console), so no additional installation is needed in most cases.

  2. First Use Case: Locate all PHP files in a directory and its subdirectories:

    use Symfony\Component\Finder\Finder;
    
    $finder = new Finder();
    $files = $finder->files()->in(__DIR__.'/src')->name('*.php');
    
    foreach ($files as $file) {
        echo $file->getRealPath() . "\n";
    }
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. Basic File Discovery:

    $finder = new Finder();
    $finder->files()->in('/path/to/dir')->name('*.{php,js}');
    
  2. Directory Filtering:

    $finder->directories()->in('/path')->depth('== 2')->name('/vendor/');
    
  3. Combining Conditions:

    $finder->files()
        ->in(__DIR__)
        ->name('*.md')
        ->notName('README.md')
        ->ignoreDotFiles(true)
        ->sortByModifiedTime();
    
  4. Lazy Iteration with Collections:

    use Illuminate\Support\Collection;
    
    $collection = Collection::make(iterator_to_array($finder->files()->in(storage_path('app'))));
    $collection->each(fn ($file) => Log::info($file->getPathname()));
    
  5. Integration with Laravel Artisan:

    use Symfony\Component\Finder\Finder;
    use Illuminate\Console\Command;
    
    class OptimizeAssets extends Command
    {
        protected $signature = 'assets:optimize';
        protected $description = 'Optimize all assets in the public directory';
    
        public function handle()
        {
            $finder = new Finder();
            $files = $finder->files()->in(public_path())->name('*.{png,jpg}');
    
            foreach ($files as $file) {
                $this->optimizeImage($file->getRealPath());
            }
        }
    }
    
  6. Dependency Injection in Laravel:

    use Symfony\Component\Finder\Finder;
    use Illuminate\Support\ServiceProvider;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(Finder::class, function () {
                return new Finder();
            });
        }
    }
    

    Then inject Finder into controllers/services:

    public function __construct(private Finder $finder) {}
    
  7. Custom Sorting:

    $finder->files()->sortByName()->reverseSorting();
    // Or with custom comparator:
    $finder->files()->sort(function ($a, $b) {
        return $a->getMTime() <=> $b->getMTime();
    });
    
  8. Excluding Vendor Directories:

    $finder->files()->in(__DIR__)->exclude(['vendor', 'node_modules']);
    
  9. Handling Symlinks:

    $finder->files()->followLinks()->in('/path/with/symlinks');
    
  10. Filtering by File Size:

    $finder->files()->size('> 1M')->in(storage_path('logs'));
    

Workflows

  1. Asset Processing Pipeline:

    • Use Finder to locate all images in /public/assets, then process them with Laravel’s Intervention Image or Imagick.
    • Example:
      $images = $finder->files()->in(public_path('assets'))->name('*.jpg');
      foreach ($images as $image) {
          Image::make($image->getRealPath())->resize(800, 600)->save();
      }
      
  2. Dynamic Configuration Loading:

    • Load all .php files from /config/dynamic and merge them into the app’s config:
      $configFiles = $finder->files()->in(config_path('dynamic'))->name('*.php');
      foreach ($configFiles as $file) {
          $configs[$file->getFilenameWithoutExtension()] = require $file->getRealPath();
      }
      
  3. Test Fixture Management:

    • Discover all JSON fixtures in tests/Fixtures and load them for testing:
      $fixtures = $finder->files()->in(base_path('tests/Fixtures'))->name('*.json');
      foreach ($fixtures as $fixture) {
          $data = json_decode(file_get_contents($fixture->getRealPath()), true);
          // Use $data in tests
      }
      
  4. Log File Rotation:

    • Find and archive old log files:
      $oldLogs = $finder->files()
          ->in(storage_path('logs'))
          ->date('> 30 days ago')
          ->name('*.log');
      foreach ($oldLogs as $log) {
          Storage::disk('s3')->put('backups/' . $log->getFilename(), file_get_contents($log->getRealPath()));
          $log->delete();
      }
      
  5. Localization Workflow:

    • Identify untranslated files in /resources/lang:
      $untranslated = $finder->files()
          ->in(resource_path('lang'))
          ->name('*.php')
          ->not(function (\SplFileInfo $file) {
              return file_exists($file->getPathname() . '.en.php');
          });
      

Integration Tips

  1. Combine with Laravel’s Storage Facade:

    use Illuminate\Support\Facades\Storage;
    
    $files = (new Finder())->files()->in(Storage::disk('s3')->path('uploads'));
    
  2. Use with Laravel’s Filesystem Manager:

    $files = (new Finder())->files()->in($this->files->getAdapter()->getDriver()->getPathPrefix());
    
  3. Leverage in Service Providers:

    • Pre-load critical files during boot:
      public function boot()
      {
          $routes = (new Finder())->files()->in(base_path('routes'))->name('*.php');
          foreach ($routes as $routeFile) {
              require $routeFile->getRealPath();
          }
      }
      
  4. Custom Artisan Commands:

    • Build reusable CLI tools:
      $this->command('files:cleanup')
           ->describe('Remove old temporary files')
           ->action(function () {
               $finder = new Finder();
               $tempFiles = $finder->files()
                   ->in(storage_path('framework/views'))
                   ->date('> 1 day ago');
               foreach ($tempFiles as $file) {
                   $file->delete();
               }
           });
      
  5. Testing:

    • Mock Finder in unit tests:
      $finder = $this->createMock(Finder::class);
      $finder->method('files')->willReturn(new ArrayIterator([$mockFile]));
      $this->app->instance(Finder::class, $finder);
      

Gotchas and Tips

Pitfalls

  1. Glob Pattern Quirks:

    • Unanchored glob patterns (e.g., *test*) may not work as expected. Use Finder::create() with explicit paths or anchor patterns (e.g., */test*).
    • Fix: Use Finder::create()->in('/path')->name('/test/') for anchored patterns.
  2. Empty Iterators:

    • Appending empty iterators can cause issues. Always validate results:
      $files = $finder->files()->in('/nonexistent')->name('*.php');
      if ($files->count() === 0) {
          // Handle empty result
      }
      
  3. Case Sensitivity:

    • On case-insensitive filesystems (e.g., Windows), name('*.PHP') may not match file.php. Use ignoreCase(true) or stick to lowercase:
      $finder->files()->name('*.php')->ignoreCase(true);
      
  4. Performance with Large Directories:

    • Avoid loading all files into memory at once. Use lazy iteration:
      foreach ($finder->files()->in('/large/dir') as $file) {
          // Process one file at a time
      }
      
  5. Symlink Handling:

    • By default, Finder does not follow symlinks. Use followLinks() to traverse symlinked directories:
      $finder->files()->followLinks()->in('/path/with/symlinks');
      
  6. Path Separators:

    • Use forward slashes (`
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