Skip to content

Commit

Permalink
Fix error handling in Stream::getContents() (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
devanych authored Nov 16, 2023
1 parent 3b4d82e commit 28838d4
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 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 @@ -89,13 +91,15 @@ public function __toString(): string
* Closes the stream and any underlying resources.
*
* @return void
* @psalm-suppress PossiblyNullArgument
*/
public function close(): void
{
if ($this->resource) {
$resource = $this->detach();
fclose($resource);

if (is_resource($resource)) {
fclose($resource);
}
}
}

Expand Down Expand Up @@ -332,15 +336,20 @@ public function getContents(): string
throw new RuntimeException('Stream is not readable.');
}

$exception = null;
$message = 'Unable to read stream contents';

set_error_handler(static function (int $errno, string $errstr) use (&$exception, $message) {
throw $exception = new RuntimeException("$message: $errstr");
});

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("$message: {$e->getMessage()}", 0, $e);
} finally {
restore_error_handler();
}

return $result;
}

/**
Expand All @@ -357,16 +366,11 @@ public function getContents(): string
*/
public function getMetadata($key = null)
{
if (!$this->resource) {
if (!is_resource($this->resource)) {
return $key ? null : [];
}

try {
$metadata = stream_get_meta_data($this->resource);
} catch (Throwable $e) {
$this->detach();
return $key ? null : [];
}
$metadata = stream_get_meta_data($this->resource);

if ($key === null) {
return $metadata;
Expand Down

0 comments on commit 28838d4

Please sign in to comment.