From d3ea2e3c1cef47729e816f650612e6e15d053e6a Mon Sep 17 00:00:00 2001 From: Evgeniy Zyubin Date: Wed, 15 Nov 2023 14:38:10 +0300 Subject: [PATCH] Fix error handling on StreamTrait::getContents() method (#28) --- src/StreamTrait.php | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/StreamTrait.php b/src/StreamTrait.php index 0138fbb..53269b8 100644 --- a/src/StreamTrait.php +++ b/src/StreamTrait.php @@ -8,7 +8,6 @@ use RuntimeException; use Throwable; -use function array_key_exists; use function fclose; use function feof; use function fopen; @@ -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; @@ -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; } /**