Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix StreamFactoryTest error #191

Merged
merged 4 commits into from
Apr 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"require-dev": {
"ext-json": "*",
"adriansuter/php-autoload-override": "^1.2",
"http-interop/http-factory-tests": "^0.8.0",
"http-interop/http-factory-tests": "^0.9.0",
"php-http/psr7-integration-tests": "dev-master",
"phpstan/phpstan": "^0.12",
"phpunit/phpunit": "^8.5 || ^9.3",
Expand Down
39 changes: 11 additions & 28 deletions src/Factory/StreamFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
use function restore_error_handler;
use function rewind;
use function set_error_handler;
use function sprintf;

class StreamFactory implements StreamFactoryInterface
{
Expand Down Expand Up @@ -54,37 +53,21 @@ public function createStreamFromFile(
string $mode = 'r',
StreamInterface $cache = null
): StreamInterface {
// 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;

// 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,
$errorMessage
));
};

set_error_handler(function (int $errno, string $errstr) use ($errorHandler) {
$errorHandler($errstr);
});
set_error_handler(
static function (int $errno, string $errstr) use ($filename, $mode): void {
throw new RuntimeException(
"Unable to open $filename using mode $mode: $errstr",
$errno
);
}
);

try {
$resource = fopen($filename, $mode);
} catch (ValueError $exception) {
$errorHandler($exception->getMessage());
}
restore_error_handler();

if ($exc) {
/** @var RuntimeException $exc */
throw $exc;
throw new RuntimeException("Unable to open $filename using mode $mode: " . $exception->getMessage());
} finally {
restore_error_handler();
}

if (!is_resource($resource)) {
Expand Down