Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: update error handling in Stream::getContents() #169

Merged
merged 2 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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