Skip to content

Commit 61a885d

Browse files
committed
✨ +StreamUtil
1 parent 722fdcd commit 61a885d

File tree

2 files changed

+44
-7
lines changed

2 files changed

+44
-7
lines changed

src/MessageUtil.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,10 @@
2222
final class MessageUtil{
2323

2424
/**
25-
* Read the message body's content and make sure we rewind
25+
* Read the message body's content
2626
*/
2727
public static function getContents(MessageInterface $message):string{
28-
$body = $message->getBody();
29-
$body->rewind(); //rewind before read...
30-
$data = $body->getContents();
31-
$body->rewind(); // ...and after
32-
33-
return $data;
28+
return StreamUtil::getContents($message->getBody());
3429
}
3530

3631
/**

src/StreamUtil.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
/**
3+
* Class StreamUtil
4+
*
5+
* @created 21.07.2023
6+
* @author smiley <smiley@chillerlan.net>
7+
* @copyright 2023 smiley
8+
* @license MIT
9+
*/
10+
11+
namespace chillerlan\HTTP\Utils;
12+
13+
use Psr\Http\Message\StreamInterface;
14+
15+
/**
16+
*
17+
*/
18+
class StreamUtil{
19+
20+
/**
21+
* Reads the content from a stream and make sure we rewind
22+
*/
23+
public static function getContents(StreamInterface $stream):string{
24+
25+
// rewind before read...
26+
if($stream->isSeekable()){
27+
$stream->rewind();
28+
}
29+
30+
$data = $stream->isReadable()
31+
? $stream->getContents()
32+
: $stream->__toString();
33+
34+
// ...and after
35+
if($stream->isSeekable()){
36+
$stream->rewind();
37+
}
38+
39+
return $data;
40+
}
41+
42+
}

0 commit comments

Comments
 (0)