Skip to content

Commit 96c4dd0

Browse files
committed
Add shortcut for parsing a valid open stream
1 parent 8c70a9c commit 96c4dd0

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/ResourceStream.php

+16
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,22 @@ public function __construct(
3131
$this->unwrap();
3232
}
3333

34+
/**
35+
* @param mixed $resource
36+
*
37+
* @psalm-assert resource $resource
38+
*
39+
* @throws RuntimeException
40+
*/
41+
public static function parse(mixed $resource): self
42+
{
43+
if (!is_resource($resource)) {
44+
throw ResourceStreamException::noResource();
45+
}
46+
47+
return new self($resource);
48+
}
49+
3450
public function __destruct()
3551
{
3652
if (!$this->keepAlive) {

tests/Unit/ResourceStreamTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,22 @@ public function it_detects_closed_streams_during_construction(): void
2424
new ResourceStream($f);
2525
}
2626

27+
#[Test]
28+
public function it_can_parse_a_valid_stream(): void
29+
{
30+
$f = fopen('php://memory', 'r');
31+
$resourceStream = ResourceStream::parse($f);
32+
33+
self::assertSame($f, $resourceStream->unwrap());
34+
}
35+
36+
#[Test]
37+
public function it_can_parse_a_mixed_value_to_be_a_stream(): void
38+
{
39+
$this->expectException(ResourceStreamException::class);
40+
ResourceStream::parse('no-stream');
41+
}
42+
2743
#[Test]
2844
public function it_can_unwrap_a_stream(): void
2945
{

0 commit comments

Comments
 (0)