Completed
Pull Request — master (#54)
by Stefan
05:14 queued 03:10
created

SheetFile::rewind()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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