Completed
Pull Request — master (#175)
by Ilya
03:28
created

Worksheet::close()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
ccs 5
cts 5
cp 1
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Box\Spout\Writer\XLSX\Internal;
4
5
use Box\Spout\Common\Exception\InvalidArgumentException;
6
use Box\Spout\Common\Exception\IOException;
7
use Box\Spout\Writer\Common\Helper\CellHelper;
8
use Box\Spout\Writer\Common\Internal\WorksheetInterface;
9
10
/**
11
 * Class Worksheet
12
 * Represents a worksheet within a XLSX file. The difference with the Sheet object is
13
 * that this class provides an interface to write data
14
 *
15
 * @package Box\Spout\Writer\XLSX\Internal
16
 */
17
class Worksheet implements WorksheetInterface
18
{
19
    const SHEET_XML_FILE_HEADER = <<<EOD
20
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
21
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
22
EOD;
23
24
    /** @var \Box\Spout\Writer\Common\Sheet The "external" sheet */
25
    protected $externalSheet;
26
27
    /** @var string Path to the XML file that will contain the sheet data */
28
    protected $worksheetFilePath;
29
30
    /** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
31
    protected $sharedStringsHelper;
32
33
    /** @var bool Whether inline or shared strings should be used */
34
    protected $shouldUseInlineStrings;
35
36
    /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
37
    protected $stringsEscaper;
38
39
    /** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
40
    protected $sheetFilePointer;
41
42
    /** @var int Index of the last written row */
43
    protected $lastWrittenRowIndex = 0;
44
45
    /**
46
     * @param \Box\Spout\Writer\Common\Sheet $externalSheet The associated "external" sheet
47
     * @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
48
     * @param \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper $sharedStringsHelper Helper for shared strings
49
     * @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
50
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
51
     */
52 96
    public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $shouldUseInlineStrings)
53
    {
54 96
        $this->externalSheet = $externalSheet;
55 96
        $this->sharedStringsHelper = $sharedStringsHelper;
56 96
        $this->shouldUseInlineStrings = $shouldUseInlineStrings;
57
58
        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
59 96
        $this->stringsEscaper = new \Box\Spout\Common\Escaper\XLSX();
60
61 96
        $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
62 96
        $this->startSheet();
63 96
    }
64
65
    /**
66
     * Prepares the worksheet to accept data
67
     *
68
     * @return void
69
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
70
     */
71 96
    protected function startSheet()
72
    {
73 96
        $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
74 96
        $this->throwIfSheetFilePointerIsNotAvailable();
75
76 96
        fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
77 96
        fwrite($this->sheetFilePointer, '<sheetData>');
78 96
    }
79
80
    /**
81
     * Checks if the book has been created. Throws an exception if not created yet.
82
     *
83
     * @return void
84
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
85
     */
86 96
    protected function throwIfSheetFilePointerIsNotAvailable()
87
    {
88 96
        if (!$this->sheetFilePointer) {
89
            throw new IOException('Unable to open sheet for writing.');
90
        }
91 96
    }
92
93
    /**
94
     * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
95
     */
96 66
    public function getExternalSheet()
97
    {
98 66
        return $this->externalSheet;
99
    }
100
101
    /**
102
     * @return int The index of the last written row
103
     */
104 60
    public function getLastWrittenRowIndex()
105
    {
106 60
        return $this->lastWrittenRowIndex;
107
    }
108
109
    /**
110
     * @return int The ID of the worksheet
111
     */
112 63
    public function getId()
113
    {
114
        // sheet index is zero-based, while ID is 1-based
115 63
        return $this->externalSheet->getIndex() + 1;
116
    }
117
118
    /**
119
     * Adds data to the worksheet.
120
     *
121
     * @param array $dataRow Array containing data to be written. Cannot be empty.
122
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
123
     * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
124
     * @return void
125
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
126
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
127
     */
128 60
    public function addRow($dataRow, $style)
129
    {
130 60
        $cellNumber = 0;
131 60
        $rowIndex = $this->lastWrittenRowIndex + 1;
132 60
        $numCells = count($dataRow);
133
134 60
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
135
136 60
        foreach($dataRow as $cellValue) {
137 60
            $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
138 60
            $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
139 60
            $cellXML .= ' s="' . $style->getId() . '"';
140
141 60
            if (CellHelper::isNonEmptyString($cellValue)) {
142 57
                if ($this->shouldUseInlineStrings) {
143 48
                    $cellXML .= ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
144 48
                } else {
145 9
                    $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
146 9
                    $cellXML .= ' t="s"><v>' . $sharedStringId . '</v></c>';
147
                }
148 60
            } else if (CellHelper::isBoolean($cellValue)) {
149 3
                if ($cellValue === true) {
150 3
                    $cellXML .= ' t="b"><v>1</v></c>';
151 3
                } else {
152
                    $cellXML .= ' t="b"><v>0</v></c>';
153
                }
154 6
            } else if (CellHelper::isNumeric($cellValue)) {
155 3
                $cellXML .= '><v>' . $cellValue . '</v></c>';
156 6
            } else if (empty($cellValue)) {
157
                // don't write empty cells (not appending to $cellXML is the right behavior!)
158 3
                $cellXML = '';
159 3
            } else {
160 3
                throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
161
            }
162
163 57
            $rowXML .= $cellXML;
164 57
            $cellNumber++;
165 57
        }
166
167 57
        $rowXML .= '</row>';
168
169 57
        $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
170 57
        if ($wasWriteSuccessful === false) {
171
            throw new IOException("Unable to write data in {$this->worksheetFilePath}");
172
        }
173
174
        // only update the count if the write worked
175 57
        $this->lastWrittenRowIndex++;
176 57
    }
177
178
    /**
179
     * Closes the worksheet
180
     *
181
     * @return void
182
     */
183 63
    public function close()
184
    {
185 63
        fwrite($this->sheetFilePointer, '</sheetData>');
186 63
        fwrite($this->sheetFilePointer, '</worksheet>');
187 63
        fclose($this->sheetFilePointer);
188 63
    }
189
}
190