devanych/mime-types

将 MIME 类型转换为文件扩展名,反之亦然

2.1.2 2020-12-12 18:53 UTC

This package is auto-updated.

Last update: 2024-08-27 21:20:20 UTC


README

License Latest Stable Version Total Downloads GitHub Build Status GitHub Static Analysis Status Scrutinizer Code Coverage Scrutinizer Code Quality

此 PHP 包允许您将 MIME 类型转换为文件扩展名,反之亦然,并添加您自己的 MIME 类型和文件扩展名。

您可以通过实现接口来更改功能

一份包含详细描述的俄语指南可在此处获得 这里

安装

此包需要 PHP 版本 7.4 或更高版本。

composer require devanych/mime-types

MimeTypes 使用方法

创建

use Devanych\Mime\MimeTypes;

$mimeTypes = new MimeTypes();

转换

/**
 * Gets the MIME types for the given file extension.
 *
 * @param string $extension
 * @return string[] an array of MIME types or an empty array if no match is found
 */
$mimeTypes->getMimeTypes('jpeg'); // ['image/jpeg', 'image/pjpeg']

/**
 * Gets the file extensions for the given MIME type.
 *
 * @param string $mimeType
 * @return string[] an array of extensions or an empty array if no match is found
 */
$mimeTypes->getExtensions('image/jpeg'); // ['jpeg', 'jpg', 'jpe']

添加

/**
 * Adds a custom map of MIME types and file extensions.
 *
 * The key is a MIME type and the value is an array of extensions.
 *
 * Example code:
 *
 * $map = [
 *    'image/ico' => ['ico'],
 *    'image/icon' => ['ico'],
 *    'image/jp2' => ['jp2', 'jpg2'],
 *    'image/jpeg' => ['jpeg', 'jpg', 'jpe'],
 *    'image/jpeg2000' => ['jp2', 'jpg2'],
 * ];
 *
 * If the map format is invalid, an `\InvalidArgumentException` will be thrown when the map is added.
 *
 * @param array $map
 */
$mimeTypes->addMap($map);

在创建 Devanych\Mime\MimeTypes 类时,您可以将映射传递给构造函数,在构造函数内部调用 addMap() 方法。

MimeTypesAllowed 使用方法

如果您只想使用预定义的允许的 MIME 类型和文件扩展名,则使用 Devanych\Mime\MimeTypesAllowed 而不是 Devanych\Mime\MimeTypes

use Devanych\Mime\MimeTypesAllowed;

$map = [
    'image/gif' => ['gif'],
    'image/png' => ['png'],
    'image/jpeg' => ['jpeg', 'jpg', 'jpe'],
];

$mimeTypes = new MimeTypesAllowed($map);

在创建 Devanych\Mime\MimeTypesAllowed 类的实例时,您必须传递映射。如果您传递一个空的或错误的映射,将抛出 \InvalidArgumentException 异常。

在创建 Devanych\Mime\MimeTypesAllowed 类的实例时,构造函数中会调用 addMap() 方法,但由于安全原因,如果您尝试再次调用 addMap() 方法,将抛出 \LogicException

getMimeTypes()getExtensions() 方法与 Devanych\Mime\MimeTypes 中的方法相同,但搜索仅限于在创建 Devanych\Mime\MimeTypesAllowed 类实例时传递给构造函数的预定义 MIME 类型和文件扩展名。