Weave 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

Pathinfo Laravel Package

bitandblack/pathinfo

Tiny PHP utility offering a consistent, OO wrapper around path information. Parse file paths into dirname, basename, extension, filename, and more, with simple getters and helpers for working with filesystem paths across environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require bitandblack/pathinfo
    

    No additional configuration is required for basic usage.

  2. First Use Case: Parsing Paths Replace procedural path parsing with an object-oriented approach:

    use BitAndBlack\PathInfo\PathInfo;
    
    $path = '/uploads/2023/10/avatar.jpg';
    $pathInfo = new PathInfo($path);
    
    // Extract components
    $filename = $pathInfo->getFilename(); // 'avatar.jpg'
    $extension = $pathInfo->getExtension(); // 'jpg'
    $dirname = $pathInfo->getDirname(); // '/uploads/2023/10'
    
  3. Where to Look First

    • Class Reference: Focus on methods like getPath(), getBasename(), getFilename(), getExtension(), getDirname(), and normalize().
    • Edge Cases: Test with paths containing:
      • No extension (e.g., /file).
      • Hidden files (e.g., /.hiddenfile).
      • Trailing slashes (e.g., /dir/).
      • URL-encoded characters (e.g., /dir%20name/file).

Implementation Patterns

Usage Patterns

  1. Service Layer Integration Inject PathInfo into services handling file operations:

    class FileUploadService {
        public function __construct(private PathInfo $pathInfo) {}
    
        public function processUpload($filePath) {
            $normalized = $this->pathInfo->normalize($filePath);
            // Use normalized path for storage
        }
    }
    

    Laravel-specific: Use dependency injection via the container:

    $this->app->bind(PathInfo::class, function () {
        return new PathInfo();
    });
    
  2. Request Validation Validate file paths in Laravel request pipelines:

    use Illuminate\Http\Request;
    use BitAndBlack\PathInfo\PathInfo;
    
    public function store(Request $request) {
        $path = $request->input('file_path');
        $pathInfo = new PathInfo($path);
    
        if (!$pathInfo->hasExtension()) {
            return back()->withError('Invalid file path');
        }
        // Proceed with logic
    }
    
  3. Artisan Commands Parse paths in CLI tools:

    use Illuminate\Console\Command;
    use BitAndBlack\PathInfo\PathInfo;
    
    class CleanupCommand extends Command {
        protected $signature = 'files:cleanup {path}';
    
        public function handle() {
            $pathInfo = new PathInfo($this->argument('path'));
            $files = Storage::files($pathInfo->getPath());
            // Process files
        }
    }
    
  4. Path Normalization Ensure consistent path formats for storage/comparison:

    $path1 = '/user//profile';
    $path2 = '/user/profile/';
    
    $normalized1 = (new PathInfo($path1))->normalize(); // '/user/profile'
    $normalized2 = (new PathInfo($path2))->normalize(); // '/user/profile'
    
    if ($normalized1 === $normalized2) {
        // Paths are equivalent
    }
    

Integration Tips

  • Laravel Storage Integration Combine with Laravel’s Storage facade for unified path handling:

    $pathInfo = new PathInfo($request->file('avatar')->path());
    $diskPath = $pathInfo->getDirname() . '/processed_' . $pathInfo->getFilename();
    Storage::put($diskPath, $processedImage);
    
  • Domain-Specific Extensions Extend PathInfo for custom rules (e.g., tenant-aware paths):

    class TenantPathInfo extends PathInfo {
        public function getTenantPath($tenantId) {
            return $this->normalize("/tenants/{$tenantId}{$this->getPath()}");
        }
    }
    
  • Testing Mock PathInfo in unit tests:

    $mockPathInfo = Mockery::mock(PathInfo::class);
    $mockPathInfo->shouldReceive('getFilename')->andReturn('test.jpg');
    $this->app->instance(PathInfo::class, $mockPathInfo);
    

Gotchas and Tips

Pitfalls

  1. Namespace Collisions

    • The package’s PathInfo class may conflict with Laravel’s Path facade.
    • Fix: Use a fully qualified alias:
      use BitAndBlack\PathInfo\PathInfo as CustomPathInfo;
      
  2. Windows Path Handling

    • The package may not fully normalize Windows-style paths (e.g., C:\Users\file.txt).
    • Workaround: Pre-process paths with str_replace() or use DIRECTORY_SEPARATOR.
  3. URL-Encoded Paths

    • Paths like /dir%20name/file may not decode automatically.
    • Tip: Use urldecode() before instantiating:
      $pathInfo = new PathInfo(urldecode($encodedPath));
      
  4. Empty Paths

    • Passing an empty string may throw unexpected errors.
    • Defensive Programming:
      $pathInfo = empty($path) ? new PathInfo('/') : new PathInfo($path);
      
  5. Extension Detection

    • Hidden files (e.g., .env) or files without extensions may return unexpected results.
    • Validation:
      if ($pathInfo->getExtension() === '' && !$pathInfo->isDotFile()) {
          // Handle no-extension case
      }
      

Debugging Tips

  • Log Path Components Inspect parsed paths during development:

    $pathInfo = new PathInfo($path);
    \Log::debug('Path components', [
        'path' => $pathInfo->getPath(),
        'dirname' => $pathInfo->getDirname(),
        'filename' => $pathInfo->getFilename(),
        'extension' => $pathInfo->getExtension(),
    ]);
    
  • Compare with Native Functions Verify behavior against PHP’s pathinfo():

    $native = pathinfo($path);
    $custom = [
        'dirname' => $pathInfo->getDirname(),
        'basename' => $pathInfo->getBasename(),
        'extension' => $pathInfo->getExtension(),
        'filename' => $pathInfo->getFilename(),
    ];
    

Configuration Quirks

  • No Built-in Config The package has no configuration file. All behavior is determined at runtime via method calls.

  • Immutable Design The PathInfo object is immutable. To modify a path, create a new instance:

    $newPath = (new PathInfo($originalPath))->setExtension('jpg');
    

Extension Points

  1. Custom Path Rules Override methods to enforce business logic:

    class SecurePathInfo extends PathInfo {
        public function getFilename() {
            $filename = parent::getFilename();
            return preg_replace('/[^a-z0-9_\-]/i', '_', $filename);
        }
    }
    
  2. Event Hooks Extend the class to trigger events (e.g., on path normalization):

    class EventPathInfo extends PathInfo {
        public function normalize() {
            $path = parent::normalize();
            event(new PathNormalized($path));
            return $path;
        }
    }
    
  3. Laravel Service Provider Bind a custom PathInfo implementation in AppServiceProvider:

    public function register() {
        $this->app->bind(PathInfo::class, function () {
            return new TenantPathInfo();
        });
    }
    

Performance Considerations

  • Avoid Redundant Instantiation Reuse PathInfo objects where possible:

    $pathInfo = new PathInfo($basePath);
    foreach ($files as $file) {
        $filePathInfo = new PathInfo($pathInfo->getPath() . '/' . $file);
        // Process
    }
    
  • Benchmark Complex Paths For deeply nested paths, test performance against native PHP functions:

    $start = microtime(true);
    $pathInfo = new PathInfo($deepPath);
    $time = microtime(true) - $start;
    
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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums