Completed
Push — master ( 2e5bdd...9e2471 )
by Ryuichi
05:26
created

SimpleFileWriter::write()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 21
cp 0
rs 6.7272
c 0
b 0
f 0
cc 7
crap 56
eloc 15
nc 5
nop 1
1
<?php
2
namespace WebStream\IO\Writer;
3
4
use WebStream\IO\File;
5
use WebStream\IO\FileOutputStream;
6
use WebStream\Exception\Extend\IOException;
7
8
/**
9
 * SimpleFileWriter
10
 * OutputStreamWriterを継承しているが、write以外の機能を無効にする
11
 * @author Ryuichi TANAKA.
12
 * @since 2016/02/25
13
 * @version 0.7
14
 */
15
class SimpleFileWriter extends OutputStreamWriter
16
{
17
    /**
18
     * @var string ファイルパス
19
     */
20
    private $filepath;
21
22
    /**
23
     * @var int バッファリングサイズ
24
     */
25
    private $bufferSize;
26
27
    /**
28
     * @var string 書き込みモード
29
     */
30
    private $mode;
31
32
    /**
33
     * constructor
34
     * @param string $filepath ファイルパス
35
     * @param int $bufferSize バッファリングサイズ
36
     */
37
    public function __construct($filepath, $bufferSize = null)
38
    {
39
        $dirname = dirname($filepath);
40
        $dir = new File($dirname);
41
        if (!$dir->isWritable()) {
42
            throw new IOException("Cannot writable: " . $filepath);
43
        }
44
45
        $this->filepath = $filepath;
46
        $this->bufferSize = $bufferSize;
47
        $this->mode = file_exists($this->filepath) ? 'ab' : 'wb';
48
    }
49
50
    /**
51
     * ファイルに書き込む
52
     * ファイルが存在する場合、常に追記モード
53
     * @param mixed $data 書き込みデータ
54
     */
55
    public function write($data)
56
    {
57
        $stream = fopen($this->filepath, $this->mode);
58
59
        if ($this->bufferSize !== null && stream_set_write_buffer($stream, $this->bufferSize) !== 0) {
60
            throw new IOException("Failed to change the buffer size.");
61
        }
62
63
        if (!is_resource($stream) || $stream === false) {
64
            throw new IOException("Unable open " . $this->filepath);
65
        }
66
67
        if (!flock($stream, LOCK_EX | LOCK_NB)) {
68
            throw new IOException("Cannot lock file: " . $this->filepath);
69
        }
70
71
        if (fwrite($stream, $data) === false) {
72
            flock($stream, LOCK_UN);
73
            fclose($stream);
74
            throw new IOException("Failed to write stream.");
75
        }
76
77
        fflush($stream);
78
        flock($stream, LOCK_UN);
79
        fclose($stream);
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function close()
86
    {
87
        // Nothing to do
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function flush()
94
    {
95
        // Nothing to do
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function newLine()
102
    {
103
        $this->write(PHP_EOL);
104
    }
105
}
106