diff --git a/src/Factory/StreamFactory.php b/src/Factory/StreamFactory.php index 07b92b2..df74cff 100644 --- a/src/Factory/StreamFactory.php +++ b/src/Factory/StreamFactory.php @@ -53,29 +53,35 @@ public function createStreamFromFile( string $mode = 'r', StreamInterface $cache = null ): StreamInterface { - // When fopen fails, PHP normally raises a warning. Add an error + // When fopen fails, PHP 7 normally raises a warning. Add an error // handler to check for errors and throw an exception instead. + // On PHP 8, exceptions are thrown. $exc = null; - set_error_handler(function (int $errno, string $errstr) use ($filename, $mode, &$exc) { + // Would not be initialized if fopen throws on PHP >= 8.0 + $resource = null; + + $errorHandler = function (string $errorMessage) use ($filename, $mode, &$exc) { $exc = new RuntimeException(sprintf( 'Unable to open %s using mode %s: %s', $filename, $mode, - $errstr + $errorMessage )); + }; + + set_error_handler(function (int $errno, string $errstr) use ($errorHandler) { + $errorHandler($errstr); }); try { $resource = fopen($filename, $mode); + // @codeCoverageIgnoreStart + // (Can only be executed in PHP >= 8.0) } catch (\ValueError $exception) { - throw new RuntimeException(sprintf( - 'Unable to open %s using mode %s: %s', - $filename, - $mode, - $exception->getMessage() - )); + $errorHandler($exception->getMessage()); } + // @codeCoverageIgnoreEnd restore_error_handler(); if ($exc) {