Skip to content

Commit

Permalink
Fix error handling in Stream::getContents()
Browse files Browse the repository at this point in the history
  • Loading branch information
devanych committed Nov 15, 2023
1 parent 3b4d82e commit b820bdf
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/StreamTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
use function get_resource_type;
use function is_resource;
use function is_string;
use function restore_error_handler;
use function set_error_handler;
use function stream_get_contents;
use function stream_get_meta_data;
use function strpos;
Expand Down Expand Up @@ -332,15 +334,19 @@ public function getContents(): string
throw new RuntimeException('Stream is not readable.');
}

$exception = null;

set_error_handler(static function ($type, $message) use (&$exception) {
throw $exception = new RuntimeException('Unable to read stream contents: ' . $message);
});

try {
if (($result = stream_get_contents($this->resource)) === false) {
throw new RuntimeException('Stream is detached.');
}
return stream_get_contents($this->resource);
} catch (Throwable $e) {
throw new RuntimeException('Unable to read stream contents: ' . $e->getMessage());
throw $e === $exception ? $e : new RuntimeException('Unable to read stream contents: ' . $e->getMessage(), 0, $e);
} finally {
restore_error_handler();
}

return $result;
}

/**
Expand Down

0 comments on commit b820bdf

Please sign in to comment.