Skip to content

Commit c341a6c

Browse files
committed
:octocat: StreamUtil::getContents() return null on error
1 parent 0257ea5 commit c341a6c

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/StreamUtil.php

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
use InvalidArgumentException;
1414
use Psr\Http\Message\StreamInterface;
15+
use Throwable;
1516
use function in_array;
1617
use function preg_match;
1718
use function str_contains;
@@ -99,17 +100,27 @@ public static function validateMode(string $mode):string{
99100

100101
/**
101102
* Reads the content from a stream and make sure we rewind
103+
*
104+
* Returns the stream content as a string, null if an error occurs, e.g. the StreamInterface throws.
102105
*/
103-
public static function getContents(StreamInterface $stream):string{
106+
public static function getContents(StreamInterface $stream):?string{
104107

105108
// rewind before read...
106109
if($stream->isSeekable()){
107110
$stream->rewind();
108111
}
109112

110-
$data = $stream->isReadable()
111-
? $stream->getContents()
112-
: $stream->__toString();
113+
try{
114+
$data = $stream->isReadable()
115+
// stream is readable - great!
116+
? $stream->getContents()
117+
// try the __toString() method
118+
// there's a chance the stream is implemented in such a way (might throw)
119+
: $stream->__toString(); // @codeCoverageIgnore
120+
}
121+
catch(Throwable $e){
122+
return null;
123+
}
113124

114125
// ...and after
115126
if($stream->isSeekable()){

0 commit comments

Comments
 (0)