Skip to content

Commit

Permalink
fix: update error handling in Stream::getContents() (#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
rancoud committed Nov 18, 2023
1 parent 01d60b3 commit 021d3ce
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
34 changes: 27 additions & 7 deletions src/Message/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ private function __construct()
}

/**
* @throws \Throwable
*
* @return string
*/
public function __toString(): string
Expand Down Expand Up @@ -271,6 +273,7 @@ public function read($length): string

/**
* @throws \RuntimeException
* @throws \Throwable
*
* @return string
*/
Expand All @@ -280,14 +283,31 @@ public function getContents(): string
throw new \RuntimeException('Unable to read stream contents');
}

$contents = \stream_get_contents($this->stream);
$exception = null;

if ($contents === false) {
// @codeCoverageIgnoreStart
/* Could not reach this statement without mocking the filesystem
*/
throw new \RuntimeException('Unable to read stream contents');
// @codeCoverageIgnoreEnd
\set_error_handler(static function ($type, $message) use (&$exception) {
throw $exception = new \RuntimeException('Unable to read stream contents: ' . $message);
});

try {
$contents = \stream_get_contents($this->stream);

if ($contents === false) {
// @codeCoverageIgnoreStart
/* Could not reach this statement without changing php-src
* @info: https://github.com/php/php-src/blob/311cae03e730c76aed343312319ed8cf1c37ade0/main/streams/streams.c#L1512
*/
$exception = new \RuntimeException('Unable to read stream contents');
// @codeCoverageIgnoreEnd
}
} catch (\Throwable $e) {
$exception = new \RuntimeException('Unable to read stream contents: ' . $e->getMessage(), 0, $e);
}

\restore_error_handler();

if ($exception) {
throw $exception;
}

return $contents;
Expand Down
14 changes: 14 additions & 0 deletions tests/StreamTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@ public function testGetsContents(): void
static::assertSame('', $stream->getContents());
}

public function testGetsContentsRaiseException(): void
{
$handle = \fopen(\tempnam(\sys_get_temp_dir(), 'rancoud/http'), 'r+');

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Unable to read stream contents');

$stream = Stream::create($handle);

\fclose($handle);

$stream->getContents();
}

public function testChecksEof(): void
{
$handle = \fopen('php://temp', 'w+');
Expand Down

0 comments on commit 021d3ce

Please sign in to comment.