Skip to content

Commit 6db6a36

Browse files
authored
Merge pull request #47 from sunrise-php/release/v3.7.0
v3.7
2 parents c3277ed + b78608f commit 6db6a36

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/Stream.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
namespace Sunrise\Http\Message;
1313

14+
use App\Exception\ExceptionFactory;
15+
use OverflowException;
1416
use Psr\Http\Message\StreamInterface;
1517
use Sunrise\Http\Message\Exception\InvalidArgumentException;
1618
use Sunrise\Http\Message\Exception\RuntimeException;
@@ -204,6 +206,24 @@ public function write($string): int
204206
return $result;
205207
}
206208

209+
/**
210+
* @since 3.7.0
211+
*
212+
* @throws OverflowException
213+
*/
214+
public function writeStream(StreamInterface $stream, int $limit = -1): int
215+
{
216+
$written = 0;
217+
while (!$stream->eof()) {
218+
$written += $this->write($stream->read(4096));
219+
if ($limit > 0 && $written > $limit) {
220+
throw new OverflowException('Maximum stream size exceeded.');
221+
}
222+
}
223+
224+
return $written;
225+
}
226+
207227
/**
208228
* @inheritDoc
209229
*/

tests/StreamTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44

55
namespace Sunrise\Http\Message\Tests;
66

7+
use OverflowException;
78
use PHPUnit\Framework\TestCase;
89
use Psr\Http\Message\StreamInterface;
910
use Sunrise\Http\Message\Exception\InvalidArgumentException;
1011
use Sunrise\Http\Message\Exception\RuntimeException;
1112
use Sunrise\Http\Message\Stream;
1213

14+
use Sunrise\Http\Message\StreamFactory;
1315
use function fclose;
1416
use function fopen;
1517
use function is_resource;
@@ -345,6 +347,20 @@ public function testWriteToUnwritableResource(): void
345347
$testStream->write('foo');
346348
}
347349

350+
public function testWriteStream(): void
351+
{
352+
$source = (new StreamFactory())->createStream('foo');
353+
self::assertSame(3, $this->testStream->writeStream($source));
354+
$this->assertSame('foo', (string) $this->testStream);
355+
}
356+
357+
public function testWriteTooLargeStream(): void
358+
{
359+
$source = (new StreamFactory())->createStream('foox');
360+
$this->expectException(OverflowException::class);
361+
$this->testStream->writeStream($source, 3);
362+
}
363+
348364
public function testIsReadable(): void
349365
{
350366
$this->assertTrue($this->testStream->isReadable());

0 commit comments

Comments
 (0)