Completed
Push — develop_3.0 ( cc9a0b...7ec0f5 )
by Adrien
02:58
created

WorksheetManager::isEmptyRow()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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