File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 1111
1212namespace Sunrise \Http \Message ;
1313
14+ use App \Exception \ExceptionFactory ;
15+ use OverflowException ;
1416use Psr \Http \Message \StreamInterface ;
1517use Sunrise \Http \Message \Exception \InvalidArgumentException ;
1618use 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 */
Original file line number Diff line number Diff line change 44
55namespace Sunrise \Http \Message \Tests ;
66
7+ use OverflowException ;
78use PHPUnit \Framework \TestCase ;
89use Psr \Http \Message \StreamInterface ;
910use Sunrise \Http \Message \Exception \InvalidArgumentException ;
1011use Sunrise \Http \Message \Exception \RuntimeException ;
1112use Sunrise \Http \Message \Stream ;
1213
14+ use Sunrise \Http \Message \StreamFactory ;
1315use function fclose ;
1416use function fopen ;
1517use 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 ());
You can’t perform that action at this time.
0 commit comments