Completed
Pull Request — master (#383)
by Hura
03:16
created

Worksheet::getCellXML()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

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