Skip to content
This repository has been archived by the owner on Dec 31, 2022. It is now read-only.

Commit

Permalink
new factory method createStreamFromTemporaryFile()
Browse files Browse the repository at this point in the history
  • Loading branch information
fenric committed Aug 5, 2021
1 parent 8ff4537 commit f58c567
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
36 changes: 33 additions & 3 deletions src/StreamFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class StreamFactory implements StreamFactoryInterface
{

/**
* {@inheritDoc}
* {@inheritdoc}
*/
public function createStream(string $content = '') : StreamInterface
{
Expand All @@ -39,7 +39,7 @@ public function createStream(string $content = '') : StreamInterface
}

/**
* {@inheritDoc}
* {@inheritdoc}
*
* @throws Exception\UnopenableStreamException If the given file does not open
*/
Expand All @@ -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);
}
}
7 changes: 7 additions & 0 deletions tests/StreamFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')));
}
}

0 comments on commit f58c567

Please sign in to comment.