Skip to content

Commit

Permalink
Improve performance of creating streams from strings (#241)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Apr 20, 2023
1 parent 083ce36 commit 21644a7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/Stream.php
Expand Up @@ -81,7 +81,14 @@ public static function create($body = ''): StreamInterface
}

if (\is_string($body)) {
$body = self::openZvalStream($body);
if (200000 <= \strlen($body)) {
$body = self::openZvalStream($body);
} else {
$resource = \fopen('php://memory', 'r+');
\fwrite($resource, $body);
\fseek($resource, 0);
$body = $resource;
}
}

if (!\is_resource($body)) {
Expand Down
11 changes: 8 additions & 3 deletions tests/StreamTest.php
Expand Up @@ -29,16 +29,21 @@ public function testConstructorInitializesProperties()

public function testConstructorSeekWithStringContent()
{
$stream = Stream::create('Hello');
$content = \str_repeat('Hello', 50000);
$stream = Stream::create($content);
$this->assertTrue($stream->isReadable());
$this->assertTrue($stream->isWritable());
$this->assertTrue($stream->isSeekable());
$this->assertEquals('Nyholm-Psr7-Zval://', $stream->getMetadata('uri'));
$this->assertTrue(\is_array($stream->getMetadata()));
$this->assertSame(5, $stream->getSize());
$this->assertSame(250000, $stream->getSize());
$this->assertFalse($stream->eof());
$this->assertSame('Hello', $stream->getContents());
$this->assertSame($content, $stream->getContents());
$stream->close();

$stream = Stream::create('Hello');
$this->assertEquals('php://memory', $stream->getMetadata('uri'));
$this->assertSame('Hello', $stream->getContents());
}

public function testStreamClosesHandleOnDestruct()
Expand Down

0 comments on commit 21644a7

Please sign in to comment.