Skip to content

Commit

Permalink
Fix error handling on stream getContents method
Browse files Browse the repository at this point in the history
  • Loading branch information
devanych authored Nov 15, 2023
1 parent 6c3352c commit 2500169
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/StreamTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use RuntimeException;
use Throwable;

use function array_key_exists;
use function fclose;
use function feof;
use function fopen;
Expand Down Expand Up @@ -330,8 +329,12 @@ public function getContents(): string
throw new RuntimeException('Stream is not readable.');
}

if (($result = stream_get_contents($this->resource)) === false) {
throw new RuntimeException('Error reading stream.');
try {
if (($result = stream_get_contents($this->resource)) === false) {
throw new RuntimeException('Stream is detached.');
}
} catch (Throwable $e) {
throw new RuntimeException('Unable to read stream contents: ' . $e->getMessage());
}

return $result;
Expand All @@ -358,19 +361,14 @@ public function getMetadata($key = null)
try {
$metadata = stream_get_meta_data($this->resource);
} catch (Throwable $e) {
$this->detach();
throw new RuntimeException('Unable to read stream contents: ' . $e->getMessage());
return $key ? null : [];
}

if ($key === null) {
return $metadata;
}

if (array_key_exists($key, $metadata)) {
return $metadata[$key];
}

return null;
return $metadata[$key] ?? null;
}

/**
Expand Down

0 comments on commit 2500169

Please sign in to comment.