Skip to content

Commit 28838d4

Browse files
authored
Fix error handling in Stream::getContents() (#29)
1 parent 3b4d82e commit 28838d4

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

src/StreamTrait.php

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
use function get_resource_type;
2020
use function is_resource;
2121
use function is_string;
22+
use function restore_error_handler;
23+
use function set_error_handler;
2224
use function stream_get_contents;
2325
use function stream_get_meta_data;
2426
use function strpos;
@@ -89,13 +91,15 @@ public function __toString(): string
8991
* Closes the stream and any underlying resources.
9092
*
9193
* @return void
92-
* @psalm-suppress PossiblyNullArgument
9394
*/
9495
public function close(): void
9596
{
9697
if ($this->resource) {
9798
$resource = $this->detach();
98-
fclose($resource);
99+
100+
if (is_resource($resource)) {
101+
fclose($resource);
102+
}
99103
}
100104
}
101105

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

339+
$exception = null;
340+
$message = 'Unable to read stream contents';
341+
342+
set_error_handler(static function (int $errno, string $errstr) use (&$exception, $message) {
343+
throw $exception = new RuntimeException("$message: $errstr");
344+
});
345+
335346
try {
336-
if (($result = stream_get_contents($this->resource)) === false) {
337-
throw new RuntimeException('Stream is detached.');
338-
}
347+
return stream_get_contents($this->resource);
339348
} catch (Throwable $e) {
340-
throw new RuntimeException('Unable to read stream contents: ' . $e->getMessage());
349+
throw $e === $exception ? $e : new RuntimeException("$message: {$e->getMessage()}", 0, $e);
350+
} finally {
351+
restore_error_handler();
341352
}
342-
343-
return $result;
344353
}
345354

346355
/**
@@ -357,16 +366,11 @@ public function getContents(): string
357366
*/
358367
public function getMetadata($key = null)
359368
{
360-
if (!$this->resource) {
369+
if (!is_resource($this->resource)) {
361370
return $key ? null : [];
362371
}
363372

364-
try {
365-
$metadata = stream_get_meta_data($this->resource);
366-
} catch (Throwable $e) {
367-
$this->detach();
368-
return $key ? null : [];
369-
}
373+
$metadata = stream_get_meta_data($this->resource);
370374

371375
if ($key === null) {
372376
return $metadata;

0 commit comments

Comments
 (0)