-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileOutputStream.php
115 lines (99 loc) · 3.06 KB
/
FileOutputStream.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
namespace WebStream\IO;
use WebStream\Exception\Extend\InvalidArgumentException;
use WebStream\Exception\Extend\IOException;
/**
* FileOutputStream
* @author Ryuichi TANAKA.
* @since 2016/02/24
* @version 0.7
*/
class FileOutputStream extends OutputStream
{
/**
* @var File ファイルオブジェクト
*/
protected File $file;
/**
* constructor
* @param mixed $file ファイルオブジェクトまたはファイルパス
* @param bool $isAppend 追記フラグ
* @throws InvalidArgumentException
* @throws IOException
*/
public function __construct($file, bool $isAppend = false)
{
$filepath = null;
if ($file instanceof File) {
$this->file = $file;
$filepath = $this->file->getFilePath();
} elseif (is_string($file)) {
if (!file_exists($file)) {
$dirname = dirname($file);
$dir = new File($dirname);
if (!$dir->isWritable()) {
throw new IOException("Cannot writable: " . $dirname);
}
}
$this->file = new File($file);
$filepath = $this->file->getFilePath();
} else {
throw new InvalidArgumentException("Invalid argument type: " . $file);
}
$mode = $isAppend ? 'ab' : 'wb';
$stream = fopen($filepath, $mode);
if (!is_resource($stream) || $stream === false) {
throw new IOException("Unable open " . $this->file->getFilePath());
}
if (!flock($stream, LOCK_EX | LOCK_NB)) {
throw new IOException("Cannot lock file: " . $this->file->getFilePath());
}
parent::__construct($stream);
}
/**
* {@inheritdoc}
*/
public function write($buf, int $off = null, int $len = null)
{
$data = null;
if ($off === null && $len === null) {
$data = $buf;
} elseif ($off !== null && $len === null) {
$data = substr($buf, $off);
} elseif ($off === null && $len !== null) {
$data = substr($buf, 0, $len);
} else {
$data = substr($buf, $off, $len);
}
if (@fwrite($this->stream, $data) === false) {
throw new IOException("Failed to write stream.");
}
}
/**
* {@inheritdoc}
* @throws IOException
*/
public function close()
{
if ($this->stream === null) {
return;
}
$this->flush();
// PHP5.3.2以降はfcloseではロック解放されなくなり、明示的に開放する必要がある
flock($this->stream, LOCK_UN);
if (get_resource_type($this->stream) !== 'Unknown' && fclose($this->stream) === false) {
throw new IOException("Cannot close output stream.");
}
$this->stream = null;
}
/**
* {@inheritdoc}
* @throws IOException
*/
public function flush()
{
if (@fflush($this->stream) === false) {
throw new IOException("Failed to flush.");
}
}
}