From 04ba7d3387da5a265242075927dc8978f50fdbbc Mon Sep 17 00:00:00 2001 From: Jonas Renggli Date: Fri, 31 Jan 2020 15:34:19 +0100 Subject: [PATCH] BUGFIX: Detect Content-Type in GcsStorage When uploading a resource to GCS storage the Content-Type is explicitly defined in metadata options. ``` 'metadata' => [ 'contentType' => $resource->getMediaType() ] ``` However `getMediaType()` is always returning the fallback value `application/octet-stream` as it's logic is based on using the filename to determine the Content-Type. At this point the filename consists only of a sha1 or a random value. PHP's fileinfo extension has functions to detect a Content-Type based on file content. This change uses `mime_content_type()` and `finfo_*()` functions (if these are installed) to detect the Content-Type. --- Classes/GcsStorage.php | 15 +++++++++++++++ composer.json | 3 +++ 2 files changed, 18 insertions(+) diff --git a/Classes/GcsStorage.php b/Classes/GcsStorage.php index 56598b3..a5be694 100644 --- a/Classes/GcsStorage.php +++ b/Classes/GcsStorage.php @@ -237,6 +237,14 @@ public function importResourceFromContent($content, $collectionName): Persistent $resource->setSha1($sha1Hash); $resource->setMd5($md5Hash); + if ( + class_exists('\finfo') + && ($finfo = new \finfo(FILEINFO_MIME_TYPE)) + && ($mediaType = $finfo->buffer($content)) + ) { + $resource->setMediaType($mediaType); + } + $this->getCurrentBucket()->upload($content, [ 'name' => $this->keyPrefix . $sha1Hash, 'metadata' => [ @@ -429,6 +437,13 @@ protected function importTemporaryFile(string $temporaryPathAndFilename, string $resource->setSha1($sha1Hash); $resource->setMd5($md5Hash); + if ( + function_exists('mime_content_type') + && $mediaType = mime_content_type($temporaryPathAndFilename) + ) { + $resource->setMediaType($mediaType); + } + $bucket = $this->getCurrentBucket(); if (!$bucket->object($this->keyPrefix . $sha1Hash)->exists()) { try { diff --git a/composer.json b/composer.json index 59df614..1e9aff0 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,9 @@ "ext-pdo": "*", "ext-zlib": "*" }, + "suggest": { + "ext-fileinfo": "Needed to set correct MediaType in storage" + }, "autoload": { "psr-4": { "Flownative\\Google\\CloudStorage\\": "Classes"