Failed Conditions
Push — develop_3.0 ( 80553c...f9d8ad )
by Adrien
31:09
created

Worksheet::getCellXML()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 19
cts 19
cp 1
rs 6.7272
c 0
b 0
f 0
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
     */
69 46
    public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $styleHelper, $shouldUseInlineStrings)
70
    {
71 46
        $this->externalSheet = $externalSheet;
72 46
        $this->sharedStringsHelper = $sharedStringsHelper;
73 46
        $this->styleHelper = $styleHelper;
74 46
        $this->shouldUseInlineStrings = $shouldUseInlineStrings;
75
76
        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
77 46
        $this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
78 46
        $this->stringHelper = new StringHelper();
79
80 46
        $this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
81 46
        $this->startSheet();
82 46
    }
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
     */
90 46
    protected function startSheet()
91
    {
92 46
        $this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
93 46
        $this->throwIfSheetFilePointerIsNotAvailable();
94
95 46
        fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
96 46
        fwrite($this->sheetFilePointer, '<sheetData>');
97 46
    }
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
     */
105 46
    protected function throwIfSheetFilePointerIsNotAvailable()
106
    {
107 46
        if (!$this->sheetFilePointer) {
108
            throw new IOException('Unable to open sheet for writing.');
109
        }
110 46
    }
111
112
    /**
113
     * @return \Box\Spout\Writer\Common\Sheet The "external" sheet
114
     */
115 37
    public function getExternalSheet()
116
    {
117 37
        return $this->externalSheet;
118
    }
119
120
    /**
121
     * @return int The index of the last written row
122
     */
123 33
    public function getLastWrittenRowIndex()
124
    {
125 33
        return $this->lastWrittenRowIndex;
126
    }
127
128
    /**
129
     * @return int The ID of the worksheet
130
     */
131 36
    public function getId()
132
    {
133
        // sheet index is zero-based, while ID is 1-based
134 36
        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
     */
147 33
    public function addRow($dataRow, $style)
148
    {
149 33
        if (!$this->isEmptyRow($dataRow)) {
150 33
            $this->addNonEmptyRow($dataRow, $style);
151
        }
152
153 31
        $this->lastWrittenRowIndex++;
154 31
    }
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
     */
163 33
    private function isEmptyRow($dataRow)
164
    {
165 33
        $numCells = count($dataRow);
166
        // using "reset()" instead of "$dataRow[0]" because $dataRow can be an associative array
167 33
        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
     */
180 33
    private function addNonEmptyRow($dataRow, $style)
181
    {
182 33
        $cellNumber = 0;
183 33
        $rowIndex = $this->lastWrittenRowIndex + 1;
184 33
        $numCells = count($dataRow);
185
186 33
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
187
188 33
        foreach($dataRow as $cellValue) {
189 33
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId());
190 31
            $cellNumber++;
191
        }
192
193 31
        $rowXML .= '</row>';
194
195 31
        $wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
196 31
        if ($wasWriteSuccessful === false) {
197
            throw new IOException("Unable to write data in {$this->worksheetFilePath}");
198
        }
199 31
    }
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
     */
211 33
    private function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
212
    {
213 33
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
214 33
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
215 33
        $cellXML .= ' s="' . $styleId . '"';
216
217
        /** @TODO Remove code duplication with ODS writer: https://github.com/box/spout/pull/383#discussion_r113292746 */
218 33
        if ($cellValue instanceof Cell) {
219 2
            $cell = $cellValue;
220
        } else {
221 31
            $cell = new Cell($cellValue);
222
        }
223
224 33
        if ($cell->isString()) {
225 32
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue());
226 5
        } else if ($cell->isBoolean()) {
227 2
            $cellXML .= ' t="b"><v>' . intval($cell->getValue()) . '</v></c>';
228 5
        } else if ($cell->isNumeric()) {
229 2
            $cellXML .= '><v>' . $cell->getValue() . '</v></c>';
230 4
        } else if ($cell->isEmpty()) {
231 2
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
232 1
                $cellXML .= '/>';
233
            } else {
234
                // don't write empty cells that do no need styling
235
                // NOTE: not appending to $cellXML is the right behavior!!
236 2
                $cellXML = '';
237
            }
238
        } else {
239 2
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
240
        }
241
242 31
        return $cellXML;
243
    }
244
245
    /**
246
     * Returns the XML fragment for a cell containing a non empty string
247
     *
248
     * @param string $cellValue The cell value
249
     * @return string The XML fragment representing the cell
250
     * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
251
     */
252 32
    private function getCellXMLFragmentForNonEmptyString($cellValue)
253
    {
254 32
        if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
255 1
            throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
256
        }
257
258 31
        if ($this->shouldUseInlineStrings) {
259 26
            $cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
260
        } else {
261 5
            $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
262 5
            $cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
263
        }
264
265 31
        return $cellXMLFragment;
266
    }
267
268
    /**
269
     * Closes the worksheet
270
     *
271
     * @return void
272
     */
273 36
    public function close()
274
    {
275 36
        if (!is_resource($this->sheetFilePointer)) {
276
            return;
277
        }
278
279 36
        fwrite($this->sheetFilePointer, '</sheetData>');
280 36
        fwrite($this->sheetFilePointer, '</worksheet>');
281 36
        fclose($this->sheetFilePointer);
282 36
    }
283
}
284