TemporaryFile::write()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 3
Metric Value
c 3
b 0
f 3
dl 0
loc 7
rs 9.4286
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
/**
4
 * This file is part of peridot-temporary-plugin.
5
 *
6
 * (c) Noritaka Horio <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace holyshared\peridot\temporary;
13
14
use \SplFileObject;
15
use \SplFileInfo;
16
17
18
final class TemporaryFile extends TemporaryNode implements FileSystemNode
19
{
20
21
    private $file;
22
23
    public function __construct($path, $mode = FileSystemPermission::NORMAL)
24
    {
25
        $this->node = new SplFileInfo($path);
26
        touch($path);
27
        chmod($path, $mode);
28
    }
29
30
    public function open()
31
    {
32
        $this->file = $this->node->openFile('w');
33
    }
34
35
    public function close()
36
    {
37
        $this->file = null;
38
    }
39
40
    /**
41
     * Write a text
42
     *
43
     * @param string $content
44
     * @return int|null
45
     */
46
    public function write($content)
47
    {
48
        $this->openForWrite();
49
        $writtenBytes = $this->file->fwrite($content);
50
51
        return $writtenBytes;
52
    }
53
54
    /**
55
     * Write a text with newline character
56
     *
57
     * @param string $content
58
     * @return int|null
59
     */
60
    public function writeln($content)
61
    {
62
        $this->openForWrite();
63
        $writtenBytes = $this->write($content . "\n");
64
65
        return $writtenBytes;
66
    }
67
68
    protected function removeNode()
69
    {
70
        $this->close();
71
        unlink($this->getPath());
72
    }
73
74
    private function openForWrite()
75
    {
76
        if ($this->isOpened()) {
77
            return;
78
        }
79
80
        $this->open();
81
    }
82
83
    private function isOpened()
84
    {
85
        return $this->file !== null;
86
    }
87
88
}
89