/
ReadWriteHandle.php
89 lines (73 loc) 路 2.66 KB
/
ReadWriteHandle.php
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
declare(strict_types=1);
namespace Psl\File;
use Psl;
use Psl\Filesystem;
use Psl\IO;
final class ReadWriteHandle extends Internal\AbstractHandleWrapper implements ReadWriteHandleInterface
{
use IO\ReadHandleConvenienceMethodsTrait;
use IO\WriteHandleConvenienceMethodsTrait;
private ReadWriteHandleInterface $readWriteHandle;
/**
* @param resource|object $stream
*
* @throws IO\Exception\BlockingException If unable to set the stream to non-blocking mode.
* @throws Psl\Exception\InvariantViolationException If $path points to a non-file node, or it not writeable.
* @throws Filesystem\Exception\RuntimeException If unable to create $path when it does not exist.
*/
public function __construct(string $path, WriteMode $write_mode = WriteMode::OPEN_OR_CREATE)
{
$is_file = Filesystem\is_file($path);
Psl\invariant(!Filesystem\exists($path) || $is_file, 'File "%s" is not a file.', $path);
$open_or_create = $write_mode === WriteMode::OPEN_OR_CREATE;
$must_create = $write_mode === WriteMode::MUST_CREATE;
if ($must_create && $is_file) {
Psl\invariant_violation('File "%s" already exists.', $path);
}
$creating = $open_or_create || $must_create;
if (!$creating && !$is_file) {
Psl\invariant_violation('File "%s" does not exist.', $path);
}
if ((!$creating || ($open_or_create && $is_file)) && !Filesystem\is_writable($path)) {
Psl\invariant_violation('File "%s" is not writable.', $path);
}
if ($creating && !$is_file) {
Filesystem\create_file($path);
}
/**
* @psalm-suppress UndefinedPropertyFetch
* @psalm-suppress MixedArgument
*/
$this->readWriteHandle = Internal\open($path, 'r' . ((string) $write_mode->value) . '+', read: true, write: false);
parent::__construct($this->readWriteHandle);
}
/**
* {@inheritDoc}
*/
public function readImmediately(?int $max_bytes = null): string
{
return $this->readWriteHandle->readImmediately($max_bytes);
}
/**
* {@inheritDoc}
*/
public function read(?int $max_bytes = null, ?int $timeout_ms = null): string
{
return $this->readWriteHandle->read($max_bytes, $timeout_ms);
}
/**
* {@inheritDoc}
*/
public function writeImmediately(string $bytes): int
{
return $this->readWriteHandle->writeImmediately($bytes);
}
/**
* {@inheritDoc}
*/
public function write(string $bytes, ?int $timeout_ms = null): int
{
return $this->readWriteHandle->write($bytes, $timeout_ms);
}
}