diff --git a/spec/StreamFactory/StreamFactoryBehavior.php b/spec/StreamFactory/StreamFactoryBehavior.php index afc67ef..f78a1c6 100644 --- a/spec/StreamFactory/StreamFactoryBehavior.php +++ b/spec/StreamFactory/StreamFactoryBehavior.php @@ -2,6 +2,9 @@ namespace spec\Http\Message\StreamFactory; +use GuzzleHttp\Psr7\Stream; +use Psr\Http\Message\StreamInterface; + trait StreamFactoryBehavior { function it_is_a_stream_factory() @@ -32,4 +35,33 @@ function it_creates_a_stream_from_non_seekable_resource() $this->createStream($resource) ->shouldHaveType('Psr\Http\Message\StreamInterface'); } + + function it_does_not_rewind_existing_stream() + { + $stream = new Stream(fopen('php://memory', 'rw')); + $stream->write('abcdef'); + $stream->seek(3); + + $this->createStream($stream) + ->shouldHaveContent('def'); + } + + function it_does_not_rewind_existing_resource() + { + $resource = fopen('php://memory', 'rw'); + fwrite($resource, 'abcdef'); + fseek($resource, 3); + + $this->createStream($resource) + ->shouldHaveContent('def'); + } + + public function getMatchers() + { + return [ + 'haveContent' => function (StreamInterface $subject, $key) { + return $subject->getContents() === $key; + }, + ]; + } } diff --git a/src/StreamFactory/DiactorosStreamFactory.php b/src/StreamFactory/DiactorosStreamFactory.php index a73abb0..a75ec98 100644 --- a/src/StreamFactory/DiactorosStreamFactory.php +++ b/src/StreamFactory/DiactorosStreamFactory.php @@ -18,26 +18,19 @@ final class DiactorosStreamFactory implements StreamFactory */ public function createStream($body = null) { - if (!$body instanceof StreamInterface) { - if (is_resource($body)) { - $body = new Stream($body); - } else { - $stream = new Stream('php://memory', 'rw'); - - if (null === $body || '' === $body) { - return $stream; - } - - $stream->write((string) $body); + if ($body instanceof StreamInterface) { + return $body; + } - $body = $stream; - } + if (is_resource($body)) { + return new Stream($body); } - if ($body->isSeekable()) { - $body->rewind(); + $stream = new Stream('php://memory', 'rw'); + if (null !== $body && '' !== $body) { + $stream->write((string) $body); } - return $body; + return $stream; } } diff --git a/src/StreamFactory/SlimStreamFactory.php b/src/StreamFactory/SlimStreamFactory.php index ba0bb17..efcadc4 100644 --- a/src/StreamFactory/SlimStreamFactory.php +++ b/src/StreamFactory/SlimStreamFactory.php @@ -23,20 +23,13 @@ public function createStream($body = null) } if (is_resource($body)) { - $stream = new Stream($body); - } else { - $resource = fopen('php://memory', 'r+'); - $stream = new Stream($resource); - - if (null === $body || '' === $body) { - return $stream; - } - - $stream->write((string) $body); + return new Stream($body); } - if ($stream->isSeekable()) { - $stream->rewind(); + $resource = fopen('php://memory', 'r+'); + $stream = new Stream($resource); + if (null !== $body && '' !== $body) { + $stream->write((string) $body); } return $stream;