1
0
mirror of https://github.com/Intervention/image.git synced 2025-08-01 11:30:16 +02:00

NEW Allow images to be initiated from PSR StreamInterfaces

This commit is contained in:
Daniel Hensby
2017-06-26 15:29:19 +01:00
parent 274403ce35
commit 19f84f90bd
2 changed files with 28 additions and 20 deletions

View File

@@ -2,6 +2,9 @@
namespace Intervention\Image;
use GuzzleHttp\Psr7\Stream;
use Psr\Http\Message\StreamInterface;
abstract class AbstractDecoder
{
/**
@@ -85,22 +88,35 @@ abstract class AbstractDecoder
/**
* Init from given stream
*
* @param $stream
* @param StreamInterface|resource $stream
* @return \Intervention\Image\Image
*/
public function initFromStream($stream)
{
$offset = ftell($stream);
$shouldAndCanSeek = $offset !== 0 && $this->isStreamSeekable($stream);
if ($shouldAndCanSeek) {
rewind($stream);
if (!$stream instanceof StreamInterface) {
$stream = new Stream($stream);
}
$data = @stream_get_contents($stream);
try {
$offset = $stream->tell();
} catch (\RuntimeException $e) {
$offset = 0;
}
$shouldAndCanSeek = $offset !== 0 && $stream->isSeekable();
if ($shouldAndCanSeek) {
fseek($stream, $offset);
$stream->rewind();
}
try {
$data = $stream->getContents();
} catch (\RuntimeException $e) {
$data = null;
}
if ($shouldAndCanSeek) {
$stream->seek($offset);
}
if ($data) {
@@ -112,18 +128,6 @@ abstract class AbstractDecoder
);
}
/**
* Checks if we can move the pointer for this stream
*
* @param resource $stream
* @return bool
*/
private function isStreamSeekable($stream)
{
$metadata = stream_get_meta_data($stream);
return $metadata['seekable'];
}
/**
* Determines if current source data is GD resource
*
@@ -213,6 +217,7 @@ abstract class AbstractDecoder
*/
public function isStream()
{
if ($this->data instanceof StreamInterface) return true;
if (!is_resource($this->data)) return false;
if (get_resource_type($this->data) !== 'stream') return false;

View File

@@ -61,6 +61,9 @@ class AbstractDecoderTest extends PHPUnit_Framework_TestCase
$source = $this->getTestDecoder(fopen(__DIR__ . '/images/test.jpg', 'r'));
$this->assertTrue($source->isStream());
$source = $this->getTestDecoder(new \GuzzleHttp\Psr7\Stream(fopen(__DIR__ . '/images/test.jpg', 'r')));
$this->assertTrue($source->isStream());
$source = $this->getTestDecoder(null);
$this->assertFalse($source->isStream());
}