mime_content_type — 检测文件的 MIME 类型 实现,替换为基于 Mime-type Detection league/mime-type-detection 的实现

1、参考:同样的 CSS 文件(其 Etag 相等),由于 响应的 Content-Type 的差异,进而导致网页界面的差异。发现 响应的 Content-Type 是基于 mime_content_type — 检测文件的 MIME 类型 实现,最终基于 Mime-type Detection league/mime-type-detection league/mime-type-detection 实现。按内容检测,回退到按扩展检测。如图1

图1

use League\MimeTypeDetection\ExtensionMimeTypeDetector;

$this->detector = new ExtensionMimeTypeDetector();

Log::info(
 $return['asset_key'],
 [
  $return['asset_key'],
  $this->detector->detectMimeTypeFromPath($fullPath),
 ]
);
[2023-05-18 14:00:04] local.INFO: apps/internal/code-display/blocks/code-display.blade.php [
    "apps/internal/code-display/blocks/code-display.blade.php",
    "application/x-httpd-php"
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/.env.local [
    "apps/internal/comment/.env.local",
    null
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/app.json [
    "apps/internal/comment/app.json",
    "application/json"
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/assets/app.6e10b7.css [
    "apps/internal/comment/assets/app.6e10b7.css",
    "text/css"
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/assets/app.f8ed5d.js [
    "apps/internal/comment/assets/app.f8ed5d.js",
    "application/javascript"
] 
[2023-05-18 14:00:05] local.INFO: apps/internal/custom-button/assets/images/ali-express-large.8fdc24.png [
    "apps/internal/custom-button/assets/images/ali-express-large.8fdc24.png",
    "image/png"
] 
[2023-05-18 14:00:07] local.INFO: apps/internal/sharing-incentives/assets/images/sparkles.a0d182.jpg [
    "apps/internal/sharing-incentives/assets/images/sparkles.a0d182.jpg",
    "image/jpeg"
] 

2、查看生成的 Content-Type ,符合预期。当对应的扩展名不存在时,会返回 null 。此时需要回退处理一下。

Log::info(
 $return['asset_key'],
 [
  $return['asset_key'],
  $this->detector->detectMimeTypeFromPath($fullPath) ?? mime_content_type($fullPath),
 ]
);
永夜