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

Laminas Mime Laravel Package

hyperf/laminas-mime

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer in your Laravel project:

    composer require hyperf/laminas-mime
    

    (Note: Since this is a mirror of laminas/laminas-mime, ensure compatibility with Laravel’s PHP version.)

  2. First Use Case: Detecting MIME Types Use the Laminas\Mime\MimeType class to detect MIME types from file extensions or content:

    use Laminas\Mime\MimeType;
    
    $mimeType = new MimeType();
    $type = $mimeType->typeOf('path/to/file.pdf'); // Returns 'application/pdf'
    
  3. Where to Look First

    • Documentation: Refer to Laminas Mime’s official docs (mirrored here).
    • Source: Explore vendor/laminas-mime/src/ for core classes like MimeType, MimeTypeGuesser, and Message.
    • Laravel Integration: Use Laravel’s service container to bind the package (see Implementation Patterns).

Implementation Patterns

Core Workflows

  1. MIME Type Detection

    • File Extensions:
      $mime = new MimeType();
      $type = $mime->typeOf('document.txt'); // 'text/plain'
      
    • Content Sniffing:
      $guesser = new Laminas\Mime\MimeTypeGuesser();
      $type = $guesser->guess($fileContent); // Sniffs from binary data
      
  2. Email/Message Handling Use Laminas\Mime\Message to parse or construct MIME messages (e.g., emails):

    use Laminas\Mime\Message;
    
    $message = Message::fromString($rawEmail);
    $headers = $message->getHeaders(); // Parse headers, attachments, etc.
    
  3. Laravel Service Provider Binding Bind the package to Laravel’s container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Laminas\Mime\MimeType::class, function ($app) {
            return new Laminas\Mime\MimeType();
        });
    }
    

    Then inject via constructor:

    public function __construct(private Laminas\Mime\MimeType $mimeType) {}
    
  4. File Uploads Validate uploads by MIME type in Laravel’s HandleIncomingRequest trait:

    public function handle(Request $request)
    {
        $file = $request->file('document');
        $mime = app(Laminas\Mime\MimeType::class);
        if ($mime->typeOf($file->getPathname()) !== 'application/pdf') {
            throw new \Exception('Invalid file type');
        }
    }
    
  5. Custom MIME Types Extend the default MIME database (see Gotchas and Tips).


Gotchas and Tips

Pitfalls

  1. PHP Version Compatibility

    • Ensure your Laravel project uses PHP 7.4+ (Laminas Mime’s minimum requirement).
    • Test with hyperf/laminas-mime specifically, as forks may lag behind upstream.
  2. Content Sniffing Limitations

    • Sniffing is not foolproof. Malicious files may spoof MIME types.
    • Combine with file extensions for validation:
      $extensionType = $mime->typeOf('file.jpg');
      $sniffedType = $guesser->guess(file_get_contents('file.jpg'));
      if ($extensionType !== $sniffedType) {
          // Handle mismatch (e.g., block upload)
      }
      
  3. Memory Usage

    • Sniffing large files (e.g., videos) loads content into memory. Stream processing may be needed:
      $guesser->guess(fopen('large_file.mp4', 'r'));
      
  4. Caching MIME Types

    • MimeType caches results by default. Clear cache if extensions change:
      $mime = new MimeType();
      $mime->resetCache(); // Clears cached types
      

Debugging

  • Verify File Paths: Ensure typeOf() receives absolute paths or correct relative paths.
  • Check for Exceptions: MimeTypeGuesser may throw RuntimeException for unsupported types.
  • Log Unknown Types: Extend the MIME database (see below) and log unrecognized types for review.

Extension Points

  1. Custom MIME Database Override the default MIME types by extending Laminas\Mime\MimeType:

    use Laminas\Mime\MimeType;
    
    class CustomMimeType extends MimeType
    {
        public function __construct()
        {
            $this->addType('application/x-custom', 'custom');
        }
    }
    

    Bind it in Laravel’s container:

    $this->app->singleton(Laminas\Mime\MimeType::class, function ($app) {
        return new CustomMimeType();
    });
    
  2. Add Custom Sniffers Implement Laminas\Mime\MimeTypeGuesserInterface for custom content sniffing logic:

    class CustomGuesser implements MimeTypeGuesserInterface
    {
        public function guess($content): string
        {
            if (strpos($content, 'CUSTOM_MAGIC') === 0) {
                return 'application/x-custom';
            }
            return 'text/plain';
        }
    }
    

    Register it with the guesser:

    $guesser = new Laminas\Mime\MimeTypeGuesser();
    $guesser->addGuesser(new CustomGuesser());
    
  3. Laravel Filesystem Integration Use the package with Laravel’s Storage facade for cloud files:

    use Illuminate\Support\Facades\Storage;
    
    $path = Storage::path('file.pdf');
    $type = app(Laminas\Mime\MimeType::class)->typeOf($path);
    

Config Quirks

  • No Laravel Config: The package has no built-in Laravel config. Use dependency injection or environment variables for custom paths (e.g., MIME database location).
  • Default Database: The package uses a bundled MIME database. To replace it, override the getMimeTypes() method in a custom MimeType class.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky