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

Internet Media Type Laravel Package

webignition/internet-media-type

PHP library for parsing, validating and comparing internet media types (MIME types). Parse type/subtype and parameters, normalise, check wildcards, and match types against the IANA media type registry. Useful for content negotiation and HTTP handling.

View on GitHub
Deep Wiki
Context7

Getting Started

This is a framework-agnostic PHP library for parsing, validating and constructing internet media types (MIME types). It does not ship a Laravel service provider, facade or config file — you wire it in yourself.

  1. Install and pin the new minor:

    composer require "webignition/internet-media-type:^4.1"
    
  2. Look at the source tree first, not the README. Release 4.1 re-namespaced the fixers, models, parsers and exceptions, so any snippet you find online (or in the README of an older tag) may reference the pre-4.1 namespace. Run:

    find vendor/webignition/internet-media-type/src -name '*.php' | head -50
    

    and confirm the root namespace and directory layout before copying any example. The entry points you care about are the parser class and the media-type model; everything else (fixers, parameter objects, exceptions) is supporting cast.

  3. Verify autoloading resolves before writing code:

    php -r "require 'vendor/autoload.php'; var_dump(class_exists('Webignition\\InternetMediaType\\Parser\\Parser'));"
    

    Adjust the FQCN to whatever the source tree actually shows.

First use case: normalising a Content-Type header on an incoming request, or validating an uploaded file's declared MIME type, so that downstream code compares structured type/subtype/parameters instead of doing str_contains($header, 'application/json').

Implementation Patterns

Wrap it in a singleton binding. Parsing is stateless, so register one instance in a service provider rather than new-ing it in every controller:

$this->app->singleton(Parser::class, fn () => new Parser());

Inject the interface/class via constructor injection. If you want a Laravel-flavoured API, add your own thin facade or a MediaType cast — but keep the vendor classes out of your controllers so a future re-namespace (see Gotchas) is a one-file change.

Parsing and inspecting. Parse once, then read structured pieces: type, subtype and parameters (charset, boundary, etc.). Treat the parsed model as a value object — build what you need (type/subtype pair, parameter map) and let the vendor object go out of scope.

Request middleware for normalisation. A middleware that parses Accept, Content-Type and Accept-Encoding into request attributes is the highest-leverage integration. Downstream controllers then do array lookups instead of string surgery. Cache the parsed result on the request so you don't re-parse in multiple listeners.

Upload validation. Pair the parser with Laravel's own detection:

$declared = $parser->parse($file->getClientMimeType());
$detected = $file->getMimeType(); // Symfony-guessed, from file contents

Compare type/subtype only — clients routinely send text/plain; charset=utf-8 where the guessed value is bare text/plain. Never trust getClientMimeType() alone; it is attacker-controlled.

Content negotiation. Use it to parse Accept header members, but do the ranking/precedence logic yourself (or hand off to a dedicated negotiator). This package models media types; it is not a negotiation engine and will not tell you which of five Accept entries wins against your supported list.

Building media types for outbound requests. When constructing multipart bodies or proxying calls, build the media type object and serialise it rather than concatenating strings — this gets you correct quoting for parameters containing spaces or special characters.

Testing. In feature tests, hit your normalisation endpoint with a table of real-world headers (application/json;charset=UTF-8, multipart/form-data; boundary=----WebKitFormBoundary..., text/html; charset="iso-8859-1") and assert on the structured output, not on string equality.

Gotchas and Tips

4.1 is a re-namespace release — audit before upgrading. The changelog moves fixers, models, parsers and exceptions to new namespaces. use statements will not be fixed automatically by Composer, so:

  • composer update webignition/internet-media-type then immediately grep your codebase for the old namespace prefix and update every import.
  • String class references break silently: app('Old\\Namespace\\Parser'), container keys, class_exists() guards, serialised payloads in queues/cache, and any FQCN stored in config or a database column. ::class constants survive; string literals do not.
  • If you serialise parsed media-type objects into cache or a queue job payload, old serialised objects will fail to unserialise against the new class names. Flush those keys or version the cache key.
  • Run your full test suite plus any composer dump-autoload -o step in CI — classmap-authoritative autoloading can mask stale entries locally.

Exceptions are part of the contract. Invalid input (empty header, malformed parameter, illegal characters) throws rather than returning null. Wrap parse calls at trust boundaries in try/catch and convert to a 400/422; an uncaught parser exception on a user-supplied Content-Type is a trivial 500. Check which exception hierarchy applies in the 4.1 tree — the exceptions were re-namespaced too, so catch blocks referencing the old FQCN will silently stop catching and let errors bubble.

No config, no facade, no auto-discovery. Everything is explicit. If you want a config-driven "strict vs lenient parsing" toggle, you own that wrapper — the library gives you fixers for repairing sloppy input, which you enable by choice rather than by config flag.

Don't confuse it with the tools Laravel already ships. Illuminate\Http\Testing\MimeType, Symfony's MimeTypeGuesser, and Illuminate\Validation\Rules\File cover file-content sniffing and validation. Use this package for parsing and modelling header strings; use Symfony/Laravel for guessing from bytes. Overlapping them produces confusing double-validation.

Debugging tips. When a parse fails on a header you believe is legal, dump the raw bytes (bin2hex) — non-ASCII characters and smart quotes from copy-pasted docs are the usual culprits. If a parameter value comes back with quotes or whitespace intact, you are likely reading the pre-normalisation representation; check whether the fixer pass needs to run first. And pin the exact version in composer.json once 4.1 is live in production — a re-namespace release is a strong hint that the maintainers will keep moving things, so treat 4.x minors as potentially breaking despite the semver claim, and read the changelog on every bump.

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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
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