Completed
Push — feature/0.7.0 ( 2e2153...887737 )
by Ryuichi
03:23
created

SimpleFileWriter::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 8
nc 3
nop 2
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
 * @author Ryuichi TANAKA.
11
 * @since 2016/02/25
12
 * @version 0.7
13
 */
14
class SimpleFileWriter
15
{
16
    /**
17
     * @var string ファイルパス
18
     */
19
    private $filepath;
20
21
    /**
22
     * @var int バッファリングサイズ
23
     */
24
    private $bufferSize;
25
26
    /**
27
     * @var string 書き込みモード
28
     */
29
    private $mode;
30
31
    /**
32
     * constructor
33
     * @param string $filepath ファイルパス
34
     * @param int $bufferSize バッファリングサイズ
35
     */
36
    public function __construct($filepath, $bufferSize = null)
37
    {
38
        $dirname = dirname($filepath);
39
        $dir = new File($dirname);
40
        if (!$dir->isWritable()) {
41
            throw new IOException("Cannot writable: " . $filepath);
42
        }
43
44
        $this->filepath = $filepath;
45
        $this->bufferSize = $bufferSize;
46
        $this->mode = file_exists($this->filepath) ? 'ab' : 'wb';
47
    }
48
49
    /**
50
     * ファイルに書き込む
51
     * ファイルが存在する場合、常に追記モード
52
     * @param mixed $data 書き込みデータ
53
     */
54
    public function write($data)
55
    {
56
        $stream = fopen($this->filepath, $this->mode);
57
58
        if ($this->bufferSize !== null && stream_set_write_buffer($stream, $this->bufferSize) !== 0) {
59
            throw new IOException("Failed to change the buffer size.");
60
        }
61
62
        if (!is_resource($stream) || $stream === false) {
63
            throw new IOException("Unable open " . $this->filepath);
64
        }
65
66 View Code Duplication
        if (!flock($stream, LOCK_EX | LOCK_NB)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
            throw new IOException("Cannot lock file: " . $this->filepath);
68
        }
69
70
        if (fwrite($stream, $data) === false) {
71
            flock($stream, LOCK_UN);
72
            fclose($stream);
73
            throw new IOException("Failed to write stream.");
74
        }
75
76
        fflush($stream);
77
        flock($stream, LOCK_UN);
78
        fclose($stream);
79
    }
80
}
81