Completed
Pull Request — master (#383)
by Hura
14:11
created

Worksheet::getCellXML()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 32
rs 6.7272
ccs 17
cts 17
cp 1
cc 7
eloc 22
nc 12
nop 4
crap 7
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\Common\Helper\StringHelper;
8
use Box\Spout\Writer\Common\Cell;
9
use Box\Spout\Writer\Common\Helper\CellHelper;
10
use Box\Spout\Writer\Common\Internal\WorksheetInterface;
11
12
/**
13
 * Class Worksheet
14
 * Represents a worksheet within a XLSX file. The difference with the Sheet object is
15
 * that this class provides an interface to write data
16
 *
17
 * @package Box\Spout\Writer\XLSX\Internal
18
 */
19
class Worksheet implements WorksheetInterface
20
{
21
    /**
22
     * Maximum number of characters a cell can contain
23
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-16c69c74-3d6a-4aaf-ba35-e6eb276e8eaa [Excel 2007]
24
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 [Excel 2010]
25
     * @see https://support.office.com/en-us/article/Excel-specifications-and-limits-ca36e2dc-1f09-4620-b726-67c00b05040f [Excel 2013/2016]
26
     */
27
    const MAX_CHARACTERS_PER_CELL = 32767;
28
29
    const SHEET_XML_FILE_HEADER = <<<EOD
30
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
31
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
32
EOD;
33
34
    /** @var \Box\Spout\Writer\Common\Sheet The "external" sheet */
35
    protected $externalSheet;
36
37
    /** @var string Path to the XML file that will contain the sheet data */
38
    protected $worksheetFilePath;
39
40
    /** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
41
    protected $sharedStringsHelper;
42
43
    /** @var \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles */
44
    protected $styleHelper;
45
46
    /** @var bool Whether inline or shared strings should be used */
47
    protected $shouldUseInlineStrings;
48
49
    /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
50
    protected $stringsEscaper;
51
52
    /** @var \Box\Spout\Common\Helper\StringHelper String helper */
53
    protected $stringHelper;
54
55
    /** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
56
    protected $sheetFilePointer;
57
58
    /** @var int Index of the last written row */
59
    protected $lastWrittenRowIndex = 0;
60
61
    /**
62
     * @param \Box\Spout\Writer\Common\Sheet $externalSheet The associated "external" sheet
63
     * @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
64
     * @param \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper $sharedStringsHelper Helper for shared strings
65
     * @param \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles
66
     * @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
67
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
68 129
     */
69
    public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $styleHelper, $shouldUseInlineStrings)
70 129
    {
71 129
        $this->externalSheet = $externalSheet;
72 129
        $this->sharedStringsHelper = $sharedStringsHelper;
73 129
        $this->styleHelper = $styleHelper;
74
        $this->shouldUseInlineStrings = $shouldUseInlineStrings;
75
76 129
        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
77 129
        $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
78
        $this->stringHelper = new StringHelper();
79 129
80 129
        $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
81 129
        $this->startSheet();
82
    }
83
84
    /**
85
     * Prepares the worksheet to accept data
86
     *
87
     * @return void
88
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
89 129
     */
90
    protected function startSheet()
91 129
    {
92 129
        $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
93
        $this->throwIfSheetFilePointerIsNotAvailable();
94 129
95 129
        fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
96 129
        fwrite($this->sheetFilePointer, '<sheetData>');
97
    }
98
99
    /**
100
     * Checks if the book has been created. Throws an exception if not created yet.
101
     *
102
     * @return void
103
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
104 129
     */
105
    protected function throwIfSheetFilePointerIsNotAvailable()
106 129
    {
107
        if (!$this->sheetFilePointer) {
108
            throw new IOException('Unable to open sheet for writing.');
109 129
        }
110
    }
111
112
    /**
113
     * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
114 102
     */
115
    public function getExternalSheet()
116 102
    {
117
        return $this->externalSheet;
118
    }
119
120
    /**
121
     * @return int The index of the last written row
122 93
     */
123
    public function getLastWrittenRowIndex()
124 93
    {
125
        return $this->lastWrittenRowIndex;
126
    }
127
128
    /**
129
     * @return int The ID of the worksheet
130 99
     */
131
    public function getId()
132
    {
133 99
        // sheet index is zero-based, while ID is 1-based
134
        return $this->externalSheet->getIndex() + 1;
135
    }
136
137
    /**
138
     * Adds data to the worksheet.
139
     *
140
     * @param array $dataRow Array containing data to be written. Cannot be empty.
141
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
142
     * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
143
     * @return void
144
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
145
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
146 93
     */
147
    public function addRow($dataRow, $style)
148 93
    {
149 93
        if (!$this->isEmptyRow($dataRow)) {
150 87
            $this->addNonEmptyRow($dataRow, $style);
151
        }
152 87
153 87
        $this->lastWrittenRowIndex++;
154
    }
155
156
    /**
157
     * Returns whether the given row is empty
158
     *
159
     * @param array $dataRow Array containing data to be written. Cannot be empty.
160
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
161
     * @return bool Whether the given row is empty
162 93
     */
163
    private function isEmptyRow($dataRow)
164 93
    {
165
        $numCells = count($dataRow);
166 93
        // using "reset()" instead of "$dataRow[0]" because $dataRow can be an associative array
167
        return ($numCells === 1 && CellHelper::isEmpty(reset($dataRow)));
168
    }
169
170
    /**
171
     * Adds non empty row to the worksheet.
172
     *
173
     * @param array $dataRow Array containing data to be written. Cannot be empty.
174
     *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
175
     * @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
176
     * @return void
177
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
178
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
179 93
     */
180
    private function addNonEmptyRow($dataRow, $style)
181 93
    {
182 93
        $cellNumber = 0;
183 93
        $rowIndex = $this->lastWrittenRowIndex + 1;
184
        $numCells = count($dataRow);
185 93
186
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
187 93
188 93
        foreach($dataRow as $cellValue) {
189 87
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId());
190 87
            $cellNumber++;
191
        }
192 87
193
        $rowXML .= '</row>';
194 87
195 87
        $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
196
        if ($wasWriteSuccessful === false) {
197
            throw new IOException("Unable to write data in {$this->worksheetFilePath}");
198 87
        }
199
    }
200
201
    /**
202
     * Build and return xml for a single cell.
203
     *
204
     * @param int $rowIndex
205
     * @param int $cellNumber
206
     * @param mixed $cellValue
207
     * @param int $styleId
208
     * @return string
209
     * @throws InvalidArgumentException If the given value cannot be processed
210 93
     */
211
    private function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
212 93
    {
213 93
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
214 93
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
215
        $cellXML .= ' s="' . $styleId . '"';
216 93
217 90
        if ($cellValue instanceof Cell) {
218 90
            $cell = $cellValue;
219 3
        } else {
220 12
            $cell = new Cell($cellValue);
221 3
        }
222 12
223 6
        if ($cell->isString()) {
224 3
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue());
225 3
        } else if ($cell->isBoolean()) {
226
            $cellXML .= ' t="b"><v>' . intval($cell->getValue()) . '</v></c>';
227
        } else if ($cell->isNumeric()) {
228 6
            $cellXML .= '><v>' . $cell->getValue() . '</v></c>';
229
        } else if ($cell->isEmpty()) {
230 6
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
231 6
                $cellXML .= '/>';
232
            } else {
233
                // don't write empty cells that do no need styling
234 87
                // NOTE: not appending to $cellXML is the right behavior!!
235
                $cellXML = '';
236
            }
237
        } else {
238
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
239
        }
240
241
        return $cellXML;
242
    }
243
244 90
    /**
245
     * Returns the XML fragment for a cell containing a non empty string
246 90
     *
247 3
     * @param string $cellValue The cell value
248
     * @return string The XML fragment representing the cell
249
     * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
250 87
     */
251 78
    private function getCellXMLFragmentForNonEmptyString($cellValue)
252 78
    {
253 9
        if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
254 9
            throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
255
        }
256
257 87
        if ($this->shouldUseInlineStrings) {
258
            $cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
259
        } else {
260
            $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
261
            $cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
262
        }
263
264
        return $cellXMLFragment;
265 99
    }
266
267 99
    /**
268
     * Closes the worksheet
269
     *
270
     * @return void
271 99
     */
272 99
    public function close()
273 99
    {
274 99
        if (!is_resource($this->sheetFilePointer)) {
275
            return;
276
        }
277
278
        fwrite($this->sheetFilePointer, '</sheetData>');
279
        fwrite($this->sheetFilePointer, '</worksheet>');
280
        fclose($this->sheetFilePointer);
281
    }
282
}
283