From f58c56766abd48668058337da70bc4edf6d0eda3 Mon Sep 17 00:00:00 2001 From: Anatoly Nekhay Date: Thu, 5 Aug 2021 23:09:14 +0300 Subject: [PATCH] new factory method createStreamFromTemporaryFile() --- src/StreamFactory.php | 36 +++++++++++++++++++++++++++++++++--- tests/StreamFactoryTest.php | 7 +++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/StreamFactory.php b/src/StreamFactory.php index 0096111..d4326df 100644 --- a/src/StreamFactory.php +++ b/src/StreamFactory.php @@ -26,7 +26,7 @@ class StreamFactory implements StreamFactoryInterface { /** - * {@inheritDoc} + * {@inheritdoc} */ public function createStream(string $content = '') : StreamInterface { @@ -39,7 +39,7 @@ public function createStream(string $content = '') : StreamInterface } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws Exception\UnopenableStreamException If the given file does not open */ @@ -58,10 +58,40 @@ public function createStreamFromFile(string $filename, string $mode = 'r') : Str } /** - * {@inheritDoc} + * {@inheritdoc} */ public function createStreamFromResource($resource) : StreamInterface { return new Stream($resource); } + + /** + * Creates temporary file + * + * The temporary file is automatically removed when the stream is closed or the script ends. + * + * It isn't the PSR-7 method. + * + * @link https://www.php.net/manual/en/function.tmpfile.php + * + * @param null|string $content + * + * @return StreamInterface + * + * @throws Exception\UnopenableStreamException + */ + public function createStreamFromTemporaryFile(?string $content = null) : StreamInterface + { + $resource = \tmpfile(); + if (false === $resource) { + throw new Exception\UnopenableStreamException('Unable to create temporary file'); + } + + if (null !== $content) { + \fwrite($resource, $content); + \rewind($resource); + } + + return new Stream($resource); + } } diff --git a/tests/StreamFactoryTest.php b/tests/StreamFactoryTest.php index bfd9bfd..3af7b91 100644 --- a/tests/StreamFactoryTest.php +++ b/tests/StreamFactoryTest.php @@ -65,4 +65,11 @@ public function testCreateStreamFromUnopenableFile() (new StreamFactory)->createStreamFromFile(__DIR__ . '/nonexistent.file', 'r'); } + + public function testCreateStreamWithTemporaryFile() + { + $stream = (new StreamFactory)->createStreamFromTemporaryFile('foo'); + $this->assertTrue(\file_exists($stream->getMetadata('uri'))); + $this->assertSame('foo', \file_get_contents($stream->getMetadata('uri'))); + } }