Skip to content

Commit 7252e6d

Browse files
committed
feat: add Stream::autoClose()
1 parent 54572b0 commit 7252e6d

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ $stream = Stream::inOutput();
3434

3535
// \tmpfile()
3636
$stream = Stream::tempFile();
37+
38+
// autoclose on $stream __destruct
39+
$stream->autoClose(); // Stream
3740
```
3841

3942
### Use Stream Object

src/Stream.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ final class Stream implements \Stringable
1818
{
1919
/** @var resource */
2020
private $resource;
21+
private bool $autoClose = false;
2122

2223
/**
2324
* @param resource $resource
@@ -31,6 +32,13 @@ private function __construct($resource)
3132
$this->resource = $resource;
3233
}
3334

35+
public function __destruct()
36+
{
37+
if ($this->autoClose) {
38+
$this->close();
39+
}
40+
}
41+
3442
public function __toString(): string
3543
{
3644
return $this->contents();
@@ -85,6 +93,13 @@ public static function open(string $filename, string $mode, bool $useIncludePath
8593
return new self($handle);
8694
}
8795

96+
public function autoClose(): self
97+
{
98+
$this->autoClose = true;
99+
100+
return $this;
101+
}
102+
88103
/**
89104
* @return resource
90105
*/

tests/StreamTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,4 +217,19 @@ public function put_contents(): void
217217

218218
$this->assertSame('content', \file_get_contents($file));
219219
}
220+
221+
/**
222+
* @test
223+
*/
224+
public function can_auto_close(): void
225+
{
226+
$stream = Stream::inMemory()->autoClose();
227+
$resource = $stream->get();
228+
229+
$this->assertIsNotClosedResource($resource);
230+
231+
unset($stream);
232+
233+
$this->assertIsClosedResource($resource);
234+
}
220235
}

0 commit comments

Comments
 (0)