Skip to content

Add support for stream resources in FinfoMimeTypeDetector::detectMimeType() #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 48 additions & 5 deletions src/FinfoMimeTypeDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace League\MimeTypeDetection;

use const FILEINFO_MIME_TYPE;

use const PATHINFO_EXTENSION;
use finfo;

Expand Down Expand Up @@ -39,6 +38,11 @@ class FinfoMimeTypeDetector implements MimeTypeDetector, ExtensionLookup
*/
private $inconclusiveMimetypes;

/**
* Buffer size to read from streams if no other bufferSampleSize is defined.
*/
private const STREAM_BUFFER_SAMPLE_SIZE_DEFAULT = 4100;

public function __construct(
string $magicFile = '',
ExtensionToMimeTypeMap $extensionMap = null,
Expand All @@ -53,9 +57,17 @@ public function __construct(

public function detectMimeType(string $path, $contents): ?string
{
$mimeType = is_string($contents)
? (@$this->finfo->buffer($this->takeSample($contents)) ?: null)
: null;
$mimeType = null;
if (is_string($contents)) {
$mimeType = @$this->finfo->buffer($this->takeSample($contents));
} elseif (
is_resource($contents)
&& get_resource_type($contents) === 'stream'
&& ($streamMetaData = stream_get_meta_data($contents))
&& !empty($streamMetaData['seekable'])
) {
$mimeType = @$this->finfo->buffer($this->takeResourceSample($contents));
}

if ($mimeType !== null && ! in_array($mimeType, $this->inconclusiveMimetypes)) {
return $mimeType;
Expand Down Expand Up @@ -90,6 +102,37 @@ private function takeSample(string $contents): string
return (string) substr($contents, 0, $this->bufferSampleSize);
}

/**
* Fetches a sample of a resource while maintaining its pointer.
*/
private function takeResourceSample($contents): string
{
if (is_resource($contents) && get_resource_type($contents) === 'stream') {
// Memory optimization: given a length stream_get_contents()
// immediately allocates an internal buffer.
// However, stream_copy_to_stream() reads up to the defined length
// without pre-allocating any extra buffer.
// Given the relatively large STREAM_BUFFER_SAMPLE_SIZE_DEFAULT this
// avoids unnecessary memory hogging.
$streamContentBuffer = fopen('php://temp/maxmemory:' . self::STREAM_BUFFER_SAMPLE_SIZE_DEFAULT, 'w+b');

$streamPosition = ftell($contents);
rewind($contents);
stream_copy_to_stream(
$contents,
$streamContentBuffer,
$this->bufferSampleSize ?? self::STREAM_BUFFER_SAMPLE_SIZE_DEFAULT,
0
);
rewind($streamContentBuffer);
$streamSample = stream_get_contents($streamContentBuffer);
fclose($streamContentBuffer);
fseek($contents, $streamPosition);
return $streamSample;
}
return '';
}

public function lookupExtension(string $mimetype): ?string
{
return $this->extensionMap instanceof ExtensionLookup
Expand All @@ -103,4 +146,4 @@ public function lookupAllExtensions(string $mimetype): array
? $this->extensionMap->lookupAllExtensions($mimetype)
: [];
}
}
}
45 changes: 43 additions & 2 deletions src/FinfoMimeTypeDetectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public function detecting_from_a_file_location(): void
/**
* @test
*/
public function detecting_uses_extensions_when_a_resource_is_presented(): void
public function detecting_uses_extensions_when_a_invalid_resource_is_presented(): void
{
/** @var resource $handle */
$handle = fopen(__DIR__ . '/../test_files/flysystem.svg', 'r+');
Expand All @@ -111,4 +111,45 @@ public function detecting_uses_extensions_when_a_resource_is_presented(): void

$this->assertEquals('image/svg+xml', $mimeType);
}
}

/**
* @test
*/
public function detecting_uses_stream_contents_when_a_valid_resource_is_presented(): void
{
/** @var resource $handle */
$handle = fopen(__DIR__ . '/../test_files/flysystem.svg', 'r+');

$mimeType = $this->detector->detectMimeType('flysystem.unknown', $handle);
fclose($handle);

$this->assertEquals('image/svg+xml', $mimeType);
}

/**
* @test
*/
public function detecting_keeps_stream_contents_positions_unchanged(): void
{
/** @var resource $handle */
$handle = fopen(__DIR__ . '/../test_files/flysystem.svg', 'r+');
fseek($handle, 10);
$mimeType = $this->detector->detectMimeType('flysystem.unknown', $handle);
$this->assertEquals('image/svg+xml', $mimeType);
$this->assertEquals(10, ftell($handle));
fclose($handle);
}

/**
* @test
*/
public function detecting_non_seekable_streams_are_not_sampling(): void
{
/** @var resource $handle */
$handle = fopen('https://github.com/thephpleague/mime-type-detection', 'r');
$mimeType = $this->detector->detectMimeType('flysystem.unknown', $handle);
$this->assertEquals(null, $mimeType);
$this->assertEquals(0, ftell($handle));
fclose($handle);
}
}