Completed
Pull Request — develop_3.0 (#458)
by Adrien
01:54
created

WorksheetManager::addNonEmptyRow()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.004

Importance

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