From 98f1d991ee0c697f702afa693fb4d848e9b1c8de Mon Sep 17 00:00:00 2001 From: George Steel Date: Wed, 6 Jul 2022 20:15:00 +0100 Subject: [PATCH] Change set/restore error handler to a try/catch block Signed-off-by: George Steel --- psalm-baseline.xml | 10 ---------- src/Stream.php | 31 +++++++++++++------------------ 2 files changed, 13 insertions(+), 28 deletions(-) diff --git a/psalm-baseline.xml b/psalm-baseline.xml index 60cd6f46..6b595c35 100644 --- a/psalm-baseline.xml +++ b/psalm-baseline.xml @@ -270,13 +270,6 @@ - - - $resource - - - $resource - $resource $this->resource @@ -286,9 +279,6 @@ $stream - - is_resource($resource) - diff --git a/src/Stream.php b/src/Stream.php index 7d52147a..29c1931b 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -7,6 +7,7 @@ use GdImage; use Psr\Http\Message\StreamInterface; use RuntimeException; +use Throwable; use function array_key_exists; use function fclose; @@ -22,13 +23,11 @@ use function is_int; use function is_resource; use function is_string; -use function restore_error_handler; -use function set_error_handler; +use function sprintf; use function stream_get_contents; use function stream_get_meta_data; use function strstr; -use const E_WARNING; use const PHP_VERSION_ID; use const SEEK_SET; @@ -320,23 +319,18 @@ public function getMetadata($key = null) */ private function setStream($stream, string $mode = 'r'): void { - $error = null; $resource = $stream; if (is_string($stream)) { - set_error_handler(function ($e) use (&$error) { - if ($e !== E_WARNING) { - return; - } - - $error = $e; - }); - $resource = fopen($stream, $mode); - restore_error_handler(); - } - - if ($error) { - throw new Exception\RuntimeException('Invalid stream reference provided'); + try { + $resource = fopen($stream, $mode); + } catch (Throwable $error) { + throw new Exception\RuntimeException( + sprintf('Invalid stream reference provided: %s', $error->getMessage()), + 0, + $error + ); + } } if (! $this->isValidStreamResourceType($resource)) { @@ -355,7 +349,8 @@ private function setStream($stream, string $mode = 'r'): void /** * Determine if a resource is one of the resource types allowed to instantiate a Stream * - * @param resource $resource Stream resource. + * @param mixed $resource Stream resource. + * @psalm-assert-if-true resource $resource */ private function isValidStreamResourceType($resource): bool {