Completed
Pull Request — master (#7)
by Stefan
03:14
created

Writer::close()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
crap 1
1
<?php
2
3
namespace OneSheet;
4
5
use OneSheet\Style\Style;
6
use OneSheet\Style\Styler;
7
8
/**
9
 * Class Writer
10
 *
11
 * @package OneSheet
12
 */
13
class Writer
14
{
15
    /**
16
     * @var SheetFile
17
     */
18
    private $sheetFile;
19
20
    /**
21
     * @var Styler
22
     */
23
    private $styler;
24
25
    /**
26
     * @var Sheet
27
     */
28
    private $sheet;
29
30
    /**
31
     * @var string
32
     */
33
    private $encoding;
34
35
    /**
36
     * Writer constructor.
37
     *
38
     * @param string $encoding
39
     */
40 2
    public function __construct($encoding = 'utf-8')
41
    {
42 2
        $this->encoding = $encoding;
43 2
        $this->initialize();
44 2
    }
45
46
    /**
47
     * Initialize writer defaults.
48
     */
49 2
    private function initialize()
50
    {
51 2
        $this->sheetFile = new SheetFile();
52 2
        $this->sheetFile->fwrite(str_repeat(' ', pow(2, 20)) . '<sheetData>');
53 2
        $this->styler = new Styler();
54 2
        $this->sheet = new Sheet();
55 2
    }
56
57
    /**
58
     * @return Sheet
59
     */
60 2
    public function getSheet()
61
    {
62 2
        return $this->sheet;
63
    }
64
65
    /**
66
     * @param array $rows
67
     * @param Style $style
68
     */
69 1
    public function addRows(array $rows, Style $style = null)
70
    {
71 1
        if (count($rows) !== count($rows, COUNT_RECURSIVE)) {
72 1
            foreach ($rows as $row) {
73 1
                $this->addRow($row, $style);
74 1
            }
75 1
        }
76 1
    }
77
78
    /**
79
     * @param array $row
80
     * @param Style $style
81
     */
82 1
    public function addRow(array $row, Style $style = null)
83
    {
84 1
        $style = $style instanceof Style ? $style : $this->styler->getStyleById(0);
85 1
        $this->styler->addStyle($style);
86 1
        $this->sheetFile->fwrite($this->sheet->addRow($row, $style));
87 1
    }
88
89
    /**
90
     * Wrap things up and write/output xlsx.
91
     *
92
     * @param string $fileName
93
     */
94 1
    public function writeToFile($fileName = 'dummy.xlsx')
95
    {
96 1
        $finalizer = new Finalizer($this->sheet, $this->styler, $this->sheetFile, $this->encoding);
97 1
        $finalizer->finalize($fileName);
98 1
    }
99
}
100