xantios/mimey

PHP 包,用于将文件扩展名转换为 MIME 类型,反之亦然。

v2.2.0 2021-06-12 14:33 UTC

This package is auto-updated.

Last update: 2024-09-12 21:49:35 UTC


README

PHP 包,用于将文件扩展名转换为 MIME 类型,反之亦然。

Build Status Maintainability Latest Stable Version Downloads per Month License

此包使用 httpdmime.types 生成文件扩展名到 MIME 类型的映射,反之亦然。

mime.types 文件由 bin/generate.php 解析,并转换为优化后的 PHP 数组保存在 mime.types.php 中,然后被辅助类 \Mimey\MimeTypes 包装。

用法

$mimes = new \Mimey\MimeTypes;

// Convert extension to MIME type:
$mimes->getMimeType('json'); // application/json

// Convert MIME type to extension:
$mimes->getExtension('application/json'); // json

获取全部

很少,但有些扩展名对应多个 MIME 类型

// Get all MIME types for an extension:
$mimes->getAllMimeTypes('wmz'); // array('application/x-ms-wmz', 'application/x-msmetafile')

然而,许多 MIME 类型对应多个扩展名

// Get all extensions for a MIME type:
$mimes->getAllExtensions('image/jpeg'); // array('jpeg', 'jpg', 'jpe')

自定义转换

您可以通过更改提供给 MimeTypes 的映射来添加自定义转换。

有一个 MimeMappingBuilder 可以帮助您完成此操作

// Create a builder using the built-in conversions as the basis.
$builder = \Mimey\MimeMappingBuilder::create();

// Add a conversion. This conversion will take precedence over existing ones.
$builder->add('custom/mime-type', 'myextension');

$mimes = new \Mimey\MimeTypes($builder->getMapping());
$mimes->getMimeType('myextension'); // custom/mime-type
$mimes->getExtension('custom/mime-type'); // myextension

您可以将任意多的转换添加到构建器中

$builder->add('custom/mime-type', 'myextension');
$builder->add('foo/bar', 'foobar');
$builder->add('foo/bar', 'fbar');
$builder->add('baz/qux', 'qux');
$builder->add('cat/qux', 'qux');
...

优化自定义转换加载

您可以通过将所有转换保存为构建步骤的一部分的编译 PHP 文件来优化自定义转换的加载。

// Add a bunch of custom conversions.
$builder->add(...);
$builder->add(...);
$builder->add(...);
...
// Save the conversions to a cached file.
$builder->save($cache_file_path);

然后可以加载该文件以避免重复调用 $builder->add(...) 产生的开销

// Load the conversions from a cached file.
$builder = \Mimey\MimeMappingBuilder::load($cache_file_path);
$mimes = new \Mimey\MimeTypes($builder->getMapping());

程序化或手动添加自定义类型映射

您可以重命名包含的 mime.types.custom.examplemime.types.custom 并重新编译。自定义条目始终优于内置定义。

更新(高级)

如果有 httpd 定义的类型更新,您可以在本存储库中运行 bin/pull.php 以拉取新的 mime 文件并编译它们

安装

兼容 PHP >= 5.4。

composer require xantios/mimey

鸣谢

原始版本由 rodolfoberrios 创建