Skip to content

Commit

Permalink
Add setting a custom mimetype
Browse files Browse the repository at this point in the history
Setting a custom mimetype other than null, will
override getting the mimetype automatically when
the headers are sent.
  • Loading branch information
DigiLive committed Oct 2, 2022
1 parent 14ab931 commit 79e3079
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ your concerns remain unanswered.
* Serve a complete file.
* Serve a single byte range of a file.
* Serve multiple byte ranges of a file.
* Set a custom mimetype.

## Requirements

Expand Down
25 changes: 23 additions & 2 deletions src/FileStreamer.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ class FileStreamer
* @var false|resource Handle to the file to serve.
*/
private $filePointer;
/**
* @var string|null If not null, it defines type mimetype of the file to download.
*/
private ?string $mimeType = null;

/**
* Class Constructor.
Expand Down Expand Up @@ -90,6 +94,20 @@ public function setInline(bool $inline = true): void
$this->inline = $inline;
}

/**
* Set the mimetype of to file to serve.
*
* When not null, it overrides getting the mimetype automatically when the headers are sent.
*
* @param string|null $mimeType the mimetype of the file to serve.
*
* @return void
*/
public function setMimeType(?string $mimeType): void
{
$this->mimeType = $mimeType;
}

/**
* Start serving the file.
*
Expand Down Expand Up @@ -231,8 +249,11 @@ private function sendHeaders(int $type): void
// Get file mimetype.
$filePath = $this->fileInfo->getPathname();
$fileSize = $this->fileInfo->getSize();
$fileInfo = new finfo();
$mimeType = @$fileInfo->file($filePath, FILEINFO_MIME_TYPE);
$mimeType = $this->mimeType;
if (null === $mimeType) {
$fileInfo = new finfo();
$mimeType = @$fileInfo->file($filePath, FILEINFO_MIME_TYPE);
}

// Caching headers as IE6 workaround.
header('Pragma: public');
Expand Down
3 changes: 3 additions & 0 deletions tests/FileStreamerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ public function testStartMultiRange(): void

/**
* Test if the correct data is being served when no range is requested.
* Also, it tests setting a custom Content-Type.
*
* @return void
*/
Expand All @@ -265,8 +266,10 @@ public function testStartNoRange(): void
// Inline disposition Test.
Output::reset();
$mock->setInline(true);
$mock->setMimeType('digilive/test');

$expectedHeaders = array_merge(self::defaultHeaders, ['Content-Disposition: inline']);
$expectedHeaders[4] = 'Content-Type: digilive/test';

try {
// Suppress warning or method will be aborted.
Expand Down

0 comments on commit 79e3079

Please sign in to comment.