Skip to content

Commit

Permalink
Mimetype from file content
Browse files Browse the repository at this point in the history
  • Loading branch information
miloslavkostir committed Apr 12, 2024
1 parent 20b5a6f commit 2294371
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/AwsS3V3/AwsS3V3Adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ class AwsS3V3Adapter implements FilesystemAdapter, PublicUrlGenerator, ChecksumP
private PathPrefixer $prefixer;
private VisibilityConverter $visibility;
private MimeTypeDetector $mimeTypeDetector;
private bool $typeFromContent = false;

public function __construct(
private S3ClientInterface $client,
Expand All @@ -113,6 +114,11 @@ public function __construct(
$this->prefixer = new PathPrefixer($prefix);
$this->visibility = $visibility ?? new PortableVisibilityConverter();
$this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector();

if (isset($this->options['type_from_content'])) {
$this->typeFromContent = $this->options['type_from_content'];
unset($this->options['type_from_content']);
}
}

public function fileExists(string $path): bool
Expand Down Expand Up @@ -310,6 +316,10 @@ private function mapS3ObjectMetadata(array $metadata, string $path): StorageAttr
return new DirectoryAttributes(rtrim($path, '/'));
}

if ($this->typeFromContent) {
$metadata['ContentType'] = $this->getTypeFromContent($path);
}

$mimetype = $metadata['ContentType'] ?? null;
$fileSize = $metadata['ContentLength'] ?? $metadata['Size'] ?? null;
$fileSize = $fileSize === null ? null : (int) $fileSize;
Expand All @@ -326,6 +336,11 @@ private function mapS3ObjectMetadata(array $metadata, string $path): StorageAttr
);
}

private function getTypeFromContent(string $path): ?string
{
return $this->mimeTypeDetector->detectMimeTypeFromBuffer(fread($this->readStream($path), 1024));
}

private function extractExtraMetadata(array $metadata): array
{
$extracted = [];
Expand Down

0 comments on commit 2294371

Please sign in to comment.