Skip to content
11 changes: 8 additions & 3 deletions src/FinfoMimeTypeDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,14 @@ 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') {
$streamPosition = ftell($contents);
$mimeType = @$this->finfo->buffer(stream_get_contents($contents, $this->bufferSampleSize, 0));
fseek($contents, $streamPosition);
}

if ($mimeType !== null && ! in_array($mimeType, $this->inconclusiveMimetypes)) {
return $mimeType;
Expand Down
30 changes: 29 additions & 1 deletion 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,32 @@ 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);
}
}