-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteFile.php
More file actions
56 lines (49 loc) · 1.46 KB
/
ReadWriteFile.php
File metadata and controls
56 lines (49 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
declare(strict_types=1);
namespace StreamInterop\Impl;
use ReflectionClass;
use RuntimeException;
use StreamInterop\Interface\ClosableStream;
/**
* A lazy-ghost object for a read+write file stream; it opens the
* encapsulated resource only on first property access.
*/
class ReadWriteFile extends ReadWriteFileStream implements ClosableStream
{
/**
* @param non-empty-string $filename
*/
public function __construct(public readonly string $filename)
{
$ref = new ReflectionClass($this);
$ref->resetAsLazyGhost(
$this,
$this->openResource(...),
ReflectionClass::SKIP_INITIALIZATION_ON_SERIALIZE|ReflectionClass::SKIP_DESTRUCTOR
);
$ref->getProperty('filename')->skipLazyInitialization($this);
$ref->getProperty('filename')->setValue($this, $filename);
}
/**
* @inheritdoc
*/
public function close() : void
{
if ($this->isOpen()) {
$this->voidOrThrow(fclose($this->resource), "Could not close stream.");
}
}
protected function openResource() : void
{
$errorLevel = error_reporting(0);
error_clear_last();
$resource = fopen($this->filename, 'rb+');
error_reporting($errorLevel);
if (! $resource) {
throw new StreamException(
"Could not open rb+ resource for {$this->filename}"
);
}
$this->setResource($resource);
}
}