1919use function get_resource_type ;
2020use function is_resource ;
2121use function is_string ;
22+ use function restore_error_handler ;
23+ use function set_error_handler ;
2224use function stream_get_contents ;
2325use function stream_get_meta_data ;
2426use function strpos ;
@@ -89,13 +91,15 @@ public function __toString(): string
8991 * Closes the stream and any underlying resources.
9092 *
9193 * @return void
92- * @psalm-suppress PossiblyNullArgument
9394 */
9495 public function close (): void
9596 {
9697 if ($ this ->resource ) {
9798 $ resource = $ this ->detach ();
98- fclose ($ resource );
99+
100+ if (is_resource ($ resource )) {
101+ fclose ($ resource );
102+ }
99103 }
100104 }
101105
@@ -332,15 +336,20 @@ public function getContents(): string
332336 throw new RuntimeException ('Stream is not readable. ' );
333337 }
334338
339+ $ exception = null ;
340+ $ message = 'Unable to read stream contents ' ;
341+
342+ set_error_handler (static function (int $ errno , string $ errstr ) use (&$ exception , $ message ) {
343+ throw $ exception = new RuntimeException ("$ message: $ errstr " );
344+ });
345+
335346 try {
336- if (($ result = stream_get_contents ($ this ->resource )) === false ) {
337- throw new RuntimeException ('Stream is detached. ' );
338- }
347+ return stream_get_contents ($ this ->resource );
339348 } catch (Throwable $ e ) {
340- throw new RuntimeException ('Unable to read stream contents: ' . $ e ->getMessage ());
349+ throw $ e === $ exception ? $ e : new RuntimeException ("$ message: {$ e ->getMessage ()}" , 0 , $ e );
350+ } finally {
351+ restore_error_handler ();
341352 }
342-
343- return $ result ;
344353 }
345354
346355 /**
@@ -357,16 +366,11 @@ public function getContents(): string
357366 */
358367 public function getMetadata ($ key = null )
359368 {
360- if (!$ this ->resource ) {
369+ if (!is_resource ( $ this ->resource ) ) {
361370 return $ key ? null : [];
362371 }
363372
364- try {
365- $ metadata = stream_get_meta_data ($ this ->resource );
366- } catch (Throwable $ e ) {
367- $ this ->detach ();
368- return $ key ? null : [];
369- }
373+ $ metadata = stream_get_meta_data ($ this ->resource );
370374
371375 if ($ key === null ) {
372376 return $ metadata ;
0 commit comments