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

SheetFile   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 95.65%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 74
ccs 22
cts 23
cp 0.9565
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A fwrite() 0 8 3
A rewind() 0 8 3
A getFilePath() 0 4 1
A __destruct() 0 9 4
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