From 26e2e887481a14e10f3ea4dd9a4ad3a4d3a436aa Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 10 Nov 2023 11:00:41 +0100 Subject: [PATCH] Fix error handling in Stream::getContents() --- phpstan-baseline.neon | 5 +++++ src/Stream.php | 20 ++++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 9a0cf11..85c5e16 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -34,3 +34,8 @@ parameters: message: "#^Strict comparison using \\=\\=\\= between false and true will always evaluate to false\\.$#" count: 2 path: src/UploadedFile.php + + - + message: "#function set_error_handler expects#'" + count: 1 + path: src/Stream.php diff --git a/src/Stream.php b/src/Stream.php index d3bd78d..9aae5ef 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -260,11 +260,23 @@ public function getContents(): string throw new \RuntimeException('Stream is detached'); } - if (false === $contents = @\stream_get_contents($this->stream)) { - throw new \RuntimeException('Unable to read stream contents: ' . (\error_get_last()['message'] ?? '')); - } + $exception = null; + + \set_error_handler(static function ($type, $message) use (&$exception) { + throw $exception = new \RuntimeException('Unable to read stream contents: ' . $message); + }); - return $contents; + try { + return \stream_get_contents($this->stream); + } catch (\Throwable $e) { + if ($e === $exception) { + throw $e; + } + + throw new \RuntimeException('Unable to read stream contents: ' . $e->getMessage(), 0, $e); + } finally { + \restore_error_handler(); + } } /**