Skip to content

Commit df26efa

Browse files
committed
feat: add stream factory
1 parent 920640c commit df26efa

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

src/StreamFactory.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace MaplePHP\Http;
4+
5+
6+
use Psr\Http\Message\StreamFactoryInterface;
7+
use Psr\Http\Message\StreamInterface;
8+
use RuntimeException;
9+
10+
class StreamFactory implements StreamFactoryInterface
11+
{
12+
public function createStream(string $content = ''): StreamInterface
13+
{
14+
$stream = new Stream(Stream::TEMP);
15+
if ($content !== '') {
16+
$stream->write($content);
17+
}
18+
return $stream;
19+
}
20+
21+
public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
22+
{
23+
$stream = new Stream($filename, $mode);
24+
// PSR-17: MUST throw RuntimeException if the file cannot be opened.
25+
if (!is_resource($stream->getResource())) {
26+
throw new RuntimeException(sprintf('Unable to open file "%s" with mode "%s".', $filename, $mode));
27+
}
28+
return $stream;
29+
}
30+
31+
public function createStreamFromResource($resource): StreamInterface
32+
{
33+
// PSR-17: MUST throw InvalidArgumentException if $resource is not a resource.
34+
if (!is_resource($resource)) {
35+
throw new \InvalidArgumentException('StreamFactory::createStreamFromResource() expects a resource.');
36+
}
37+
return new Stream($resource);
38+
}
39+
40+
}

0 commit comments

Comments
 (0)