FileWriter::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 14
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
/**
4
 * This file is part of cloak.
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 cloak\writer;
13
14
use SplFileObject;
15
16
/**
17
 * Class FileWriter
18
 * @package cloak\writer
19
 */
20
class FileWriter implements Writer
21
{
22
23
    /**
24
     * @var \SplFileObject
25
     */
26
    private $file;
27
    private $writeSize = 0;
28
29
30
    /**
31
     * @param string $filePath
32
     */
33
    public function __construct($filePath)
34
    {
35
        $directoryPath = dirname($filePath);
36
37
        if (file_exists($directoryPath) === false) {
38
            throw new DirectoryNotFoundException("$directoryPath directory not found");
39
        }
40
41
        if (is_writable($directoryPath) === false) {
42
            throw new DirectoryNotWritableException("Can not write to the directory $directoryPath");
43
        }
44
45
        $this->file = new SplFileObject($filePath, 'w');
46
    }
47
48
    /**
49
     * @param string $text
50
     */
51
    public function writeText($text)
52
    {
53
        $this->write($text);
54
    }
55
56
    /**
57
     * @param string $text
58
     */
59
    public function writeLine($text)
60
    {
61
        $this->writeText($text . PHP_EOL);
62
    }
63
64
    /**
65
     * Write a blank line
66
     */
67
    public function writeEOL()
68
    {
69
        $this->write(PHP_EOL);
70
    }
71
72
    private function write($text)
73
    {
74
        $writeBytes = $this->file->fwrite($text);
75
        $this->writeSize += $writeBytes;
76
    }
77
78
    /**
79
     * @return int
80
     */
81
    public function getWriteSize()
82
    {
83
        return $this->writeSize;
84
    }
85
86
}
87