league/mime-type-detection

Flysystem 的 MIME 类型检测

1.16.0 2024-09-21 08:32 UTC

This package is auto-updated.

Last update: 2024-09-21 09:06:40 UTC


README

Author Source Code Latest Version Software License Build Status Coverage Status Quality Score Total Downloads php 7.2+

此包提供了一个基于 finfo 实现的通用 MIME 类型检测接口。

用法

composer require league/mime-type-detection

消费者接口

建议将您的代码与以下接口关联

  • League\MimetypeDetection\MimeTypeDetector
    此契约用于根据文件名和文件内容检测 MIME 类型。
  • League\MimetypeDetection\ExtensionLookup
    此契约用于查找给定文件扩展名的单个或所有 MIME 类型。自 1.13.0 版本添加。

检测器

具有扩展回退的 Finfo

$detector = new League\MimeTypeDetection\FinfoMimeTypeDetector();

// Detect by contents, fall back to detection by extension.
$mimeType = $detector->detectMimeType('some/path.php', 'string contents');

// Detect by contents only, no extension fallback.
$mimeType = $detector->detectMimeTypeFromBuffer('string contents');

// Detect by actual file, no extension fallback.
$mimeType = $detector->detectMimeTypeFromFile('existing/path.php');

// Only detect by extension
$mimeType = $detector->detectMimeTypeFromPath('any/path.php');

// Constructor options
$detector = new League\MimeTypeDetection\FinfoMimeTypeDetector(
  $pathToMimeDatabase, // Custom mime database location, default: ''
  $customExtensionMap, // Custom extension fallback mapp, default: null
  $bufferSampleSize // Buffer size limit, used to take a sample (substr) from the input buffer to reduce memory consumption.
);

仅扩展

$detector = new League\MimeTypeDetection\ExtensionMimeTypeDetector();

// Only detect by extension, ignores the file contents
$mimeType = $detector->detectMimeType('some/path.php', 'string contents');

// Always returns null
$mimeType = $detector->detectMimeTypeFromBuffer('string contents');

// Only detect by extension
$mimeType = $detector->detectMimeTypeFromFile('existing/path.php');

// Only detect by extension
$mimeType = $detector->detectMimeTypeFromPath('any/path.php');

按 MIME 类型查找扩展

此功能自版本 1.13.0 添加。

不同的实现可以查找用于给定 MIME 类型的扩展。

// string | null
$extension = $detector->lookupExtension($mime$type);

// array<string>
$allExtensions = $detector->lookupAllExtensions($mimeType);

扩展 MIME 类型查找

作为基于 finfo 的查找的回退,使用扩展映射来确定 MIME 类型。提供了一个建议的实现,该实现由 npm 包 mime-db 收集的信息生成。

提供的扩展映射

生成

$map = new League\MimeTypeDetection\GeneratedExtensionToMimeTypeMap();

// string mime-type or NULL
$mimeType = $map->lookupMimeType('png');

覆盖装饰器

$innerMap = new League\MimeTypeDetection\GeneratedExtensionToMimeTypeMap();
$map = new League\MimeTypeDetection\OverridingExtensionToMimeTypeMap($innerMap, ['png' => 'custom/mimetype']);

// string "custom/mimetype"
$mimeType = $map->lookupMimeType('png');

$map = new League\MimeTypeDetection\EmptyExtensionToMimeTypeMap();

// Always returns NULL
$mimeType = $map->lookupMimeType('png');