From e3673185673e6bf4d223ee5e3149927cf2a89aba Mon Sep 17 00:00:00 2001 From: Mika Tuupola Date: Tue, 25 Aug 2020 12:43:07 +0300 Subject: [PATCH] Fix failing file mode validation tests See https://github.com/http-interop/http-factory-tests/pull/42 --- src/StreamFactory.php | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/StreamFactory.php b/src/StreamFactory.php index adff04f..1f984b5 100644 --- a/src/StreamFactory.php +++ b/src/StreamFactory.php @@ -42,6 +42,9 @@ use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; +use InvalidArgumentException; +use RuntimeException; + class StreamFactory implements StreamFactoryInterface { /** @@ -65,11 +68,23 @@ public function createStream(string $content = ""): StreamInterface */ public function createStreamFromFile(string $filename, string $mode = "r"): StreamInterface { + if ("" === $mode || false === in_array($mode[0], ["r", "w", "a", "x", "c"])) { + throw new InvalidArgumentException( + sprintf("The mode %s is invalid.", $mode) + ); + } + if (class_exists(SlimPsr7StreamFactory::class)) { return (new SlimPsr7StreamFactory)->createStreamFromFile($filename, $mode); } - $resource = fopen($filename, $mode); + $resource = @fopen($filename, $mode); + if (false === $resource) { + throw new RuntimeException( + sprintf("The file %s cannot be opened.", $filename) + ); + } + return $this->createStreamFromResource($resource); } @@ -98,6 +113,6 @@ public function createStreamFromResource($resource): StreamInterface return new GuzzleStream($resource); } - throw new \RuntimeException("No PSR-7 implementation available"); + throw new RuntimeException("No PSR-7 implementation available"); } }