Completed
Push — master ( 520832...cb8063 )
by Stefan
03:36
created

SheetFile::fwrite()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 5
Bugs 1 Features 2
Metric Value
c 5
b 1
f 2
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 2.0625
1
<?php
2
3
namespace OneSheet;
4
5
/**
6
 * Class SheetFile, just to abstract file operations awayyy.
7
 *
8
 * @package OneSheet
9
 */
10
class SheetFile
11
{
12
    /**
13
     * @var resource
14
     */
15
    private $filePointer;
16
17
    /**
18
     * @var string
19
     */
20
    private $filePath;
21
22
    /**
23
     * SheetFile constructor.
24
     *
25
     * @throws \RuntimeException
26
     */
27 8
    public function __construct()
28
    {
29 8
        $this->filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid(null, 1) . '.xml';
30 8
        if (!$this->filePointer = fopen($this->filePath, 'wb+')) {
31
            throw new \RuntimeException("Failed to create temporary sheet file {$this->filePath}!");
32
        }
33 8
    }
34
35
    /**
36
     * Write a single string.
37
     *
38
     * @param $string
39
     */
40 8
    public function fwrite($string)
41
    {
42 8
        if (false === fwrite($this->filePointer, $string)) {
43
            throw new \RuntimeException("Failed to write to sheet file!");
44
        }
45 8
    }
46
47
    /**
48
     * Rewind file (to write header and column widths).
49
     */
50 2
    public function rewind()
51
    {
52 2
        if (false === rewind($this->filePointer)) {
53
            throw new \RuntimeException("Failed to rewind sheet file!");
54
        }
55 2
    }
56
57
    /**
58
     * Return full path of the file.
59
     *
60
     * @return string
61
     */
62 2
    public function getFilePath()
63
    {
64 2
        return $this->filePath;
65
    }
66
67
    /**
68
     * Close file pointer and delete file.
69
     */
70 8
    public function __destruct()
71
    {
72 8
        if (!fclose($this->filePointer) || !unlink($this->filePath)) {
73
            throw new \RuntimeException('Failed to close sheet file!');
74
        }
75 8
    }
76
}
77