Skip to content

Commit d3ea2e3

Browse files
authored
Fix error handling on StreamTrait::getContents() method (#28)
1 parent 6c3352c commit d3ea2e3

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/StreamTrait.php

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
use RuntimeException;
99
use Throwable;
1010

11-
use function array_key_exists;
1211
use function fclose;
1312
use function feof;
1413
use function fopen;
@@ -322,16 +321,23 @@ public function read($length): string
322321
*
323322
* @return string
324323
* @throws RuntimeException if unable to read or an error occurs while reading.
325-
* @psalm-suppress PossiblyNullArgument
326324
*/
327325
public function getContents(): string
328326
{
327+
if (!$this->resource) {
328+
throw new RuntimeException('No resource available. Cannot read.');
329+
}
330+
329331
if (!$this->isReadable()) {
330332
throw new RuntimeException('Stream is not readable.');
331333
}
332334

333-
if (($result = stream_get_contents($this->resource)) === false) {
334-
throw new RuntimeException('Error reading stream.');
335+
try {
336+
if (($result = stream_get_contents($this->resource)) === false) {
337+
throw new RuntimeException('Stream is detached.');
338+
}
339+
} catch (Throwable $e) {
340+
throw new RuntimeException('Unable to read stream contents: ' . $e->getMessage());
335341
}
336342

337343
return $result;
@@ -359,18 +365,14 @@ public function getMetadata($key = null)
359365
$metadata = stream_get_meta_data($this->resource);
360366
} catch (Throwable $e) {
361367
$this->detach();
362-
throw new RuntimeException('Unable to read stream contents: ' . $e->getMessage());
368+
return $key ? null : [];
363369
}
364370

365371
if ($key === null) {
366372
return $metadata;
367373
}
368374

369-
if (array_key_exists($key, $metadata)) {
370-
return $metadata[$key];
371-
}
372-
373-
return null;
375+
return $metadata[$key] ?? null;
374376
}
375377

376378
/**

0 commit comments

Comments
 (0)