Skip to content

Commit

Permalink
Fix error handling on StreamTrait::getContents() method (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
devanych authored Nov 15, 2023
1 parent 6c3352c commit d3ea2e3
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 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 @@ -322,16 +321,23 @@ public function read($length): string
*
* @return string
* @throws RuntimeException if unable to read or an error occurs while reading.
* @psalm-suppress PossiblyNullArgument
*/
public function getContents(): string
{
if (!$this->resource) {
throw new RuntimeException('No resource available. Cannot read.');
}

if (!$this->isReadable()) {
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 Down Expand Up @@ -359,18 +365,14 @@ public function getMetadata($key = null)
$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 d3ea2e3

Please sign in to comment.