Skip to content

Commit

Permalink
[BUGFIX] Correctly set MIME type of .js and .css files
Browse files Browse the repository at this point in the history
Resolves: #85
  • Loading branch information
cweiske committed Nov 17, 2022
1 parent d4d0d55 commit 0a8f582
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions Classes/S3Adapter/MultipartUploaderAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ class MultipartUploaderAdapter extends AbstractS3Adapter
{
const MAX_RETRIES = 10;

protected static $mimeTypeMap = [
'css' => 'text/css',
'js' => 'text/javascript',
];

/**
* @param string $localFilePath File path and name on local storage
* @param string $targetFilePath File path and name on target S3 bucket
Expand All @@ -34,10 +39,7 @@ class MultipartUploaderAdapter extends AbstractS3Adapter
*/
public function upload(string $localFilePath, string $targetFilePath, string $bucket, string $cacheControl)
{
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $localFilePath);
finfo_close($fileInfo);

$contentType = $this->detectContentType($localFilePath, $targetFilePath);
$uploader = new MultipartUploader($this->s3Client, $localFilePath, [
'bucket' => $bucket,
'key' => $targetFilePath,
Expand Down Expand Up @@ -70,4 +72,31 @@ public function upload(string $localFilePath, string $targetFilePath, string $bu
throw $e;
}
}

/**
* Detect the MIME type with finfo
*
* Fixes known wrongly detected MIME types.
*
* @return string|false Detected MIME type, false on failure
*/
private function detectContentType(string $localFilePath, string $targetFilePath)
{
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $localFilePath);
finfo_close($fileInfo);

if ($contentType === 'text/plain'
|| $contentType === 'application/octet-stream'
) {
// file's magic database often fails to detect plain text files
// we manually fix the mime type here.
$ext = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if (isset(static::$mimeTypeMap[$ext])) {
$contentType = static::$mimeTypeMap[$ext];
}
}

return $contentType;
}
}

0 comments on commit 0a8f582

Please sign in to comment.