markiewitch / mimey
PHP包,用于将文件扩展名转换为MIME类型,反之亦然。
3.0
2023-05-16 14:40 UTC
Requires
- php: ^8.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.5
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-16 18:07:50 UTC
README
PHP包,用于将文件扩展名转换为MIME类型,反之亦然。
此包使用httpd的mime.types来生成文件扩展名到MIME类型的映射,反之亦然。
mime.types
文件由bin/generate.php
解析,并转换为存储在mime.types.php
中的优化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());
安装
兼容PHP >= 5.4。
composer require ralouphie/mimey