Failed Conditions
Pull Request — master (#532)
by
unknown
03:45
created

Worksheet::getCellXML()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6

Importance

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