Completed
Pull Request — develop_3.0 (#434)
by Hura
04:17
created

WorksheetManager::addNonEmptyRow()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0021

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 15
cts 16
cp 0.9375
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 15
nc 4
nop 2
crap 3.0021
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\Entity\Cell;
9
use Box\Spout\Writer\Common\Entity\Options;
10
use Box\Spout\Writer\Common\Entity\Row;
11
use Box\Spout\Writer\Common\Entity\Worksheet;
12
use Box\Spout\Writer\Common\Helper\CellHelper;
13
use Box\Spout\Writer\Common\Manager\OptionsManagerInterface;
14
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
15
use Box\Spout\Writer\XLSX\Helper\SharedStringsHelper;
16
use Box\Spout\Writer\XLSX\Helper\StyleHelper;
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 SharedStringsHelper Helper to write shared strings */
43
    private $sharedStringsHelper;
44
45
    /** @var StyleHelper Helper to work with styles */
46
    private $styleHelper;
47
48
    /** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
49
    private $stringsEscaper;
50
51
    /** @var StringHelper String helper */
52
    private $stringHelper;
53
54
    /**
55
     * WorksheetManager constructor.
56
     *
57
     * @param OptionsManagerInterface $optionsManager
58
     * @param SharedStringsHelper $sharedStringsHelper
59
     * @param StyleHelper $styleHelper
60
     * @param \Box\Spout\Common\Escaper\XLSX $stringsEscaper
61
     * @param StringHelper $stringHelper
62
     */
63 46
    public function __construct(
64
        OptionsManagerInterface $optionsManager,
65
        SharedStringsHelper $sharedStringsHelper,
66
        StyleHelper $styleHelper,
67
        \Box\Spout\Common\Escaper\XLSX $stringsEscaper,
68
        StringHelper $stringHelper)
69
    {
70 46
        $this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS);
71 46
        $this->sharedStringsHelper = $sharedStringsHelper;
72 46
        $this->styleHelper = $styleHelper;
73 46
        $this->stringsEscaper = $stringsEscaper;
74 46
        $this->stringHelper = $stringHelper;
75 46
    }
76
77
    /**
78
     * @return SharedStringsHelper
79
     */
80 36
    public function getSharedStringsHelper()
81
    {
82 36
        return $this->sharedStringsHelper;
83
    }
84
85
86
    /**
87
     * Prepares the worksheet to accept data
88
     *
89
     * @param Worksheet $worksheet The worksheet to start
90
     * @return void
91
     * @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
92
     */
93 46
    public function startSheet(Worksheet $worksheet)
94
    {
95 46
        $sheetFilePointer = fopen($worksheet->getFilePath(), 'w');
96 46
        $this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
97
98 46
        $worksheet->setFilePointer($sheetFilePointer);
99
100 46
        fwrite($sheetFilePointer, self::SHEET_XML_FILE_HEADER);
101 46
        fwrite($sheetFilePointer, '<sheetData>');
102 46
    }
103
104
    /**
105
     * Checks if the sheet has been sucessfully created. Throws an exception if not.
106
     *
107
     * @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
108
     * @return void
109
     * @throws IOException If the sheet data file cannot be opened for writing
110
     */
111 46
    private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
112
    {
113 46
        if (!$sheetFilePointer) {
114
            throw new IOException('Unable to open sheet for writing.');
115
        }
116 46
    }
117
118
    /**
119
     * Adds a row to the worksheet.
120
     *
121
     * @param Worksheet $worksheet The worksheet to add the row to
122
     * @param Row $row The row to be added
123
     * @return void
124
     *
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, Row $row)
129
    {
130 33
        if (!$row->isEmpty()) {
131 33
            $this->addNonEmptyRow($worksheet, $row);
132
        }
133
134 31
        $worksheet->setLastWrittenRowIndex($worksheet->getLastWrittenRowIndex() + 1);
135 31
    }
136
137
    /**
138
     * Adds non empty row to the worksheet.
139
     *
140
     * @param Row $row The row to be written
141
     * @return void
142
     *
143
     * @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
144
     * @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
145
     */
146 33
    private function addNonEmptyRow(Worksheet $worksheet, Row $row)
147
    {
148 33
        $cellNumber = 0;
149 33
        $rowIndex = $worksheet->getLastWrittenRowIndex() + 1;
150 33
        $numCells = count($row->getCells());
151
152 33
        $rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
153
154
        /** @var Cell $cell */
155 33
        foreach($row->getCells() as $cell) {
156
            // Apply styles - the row style is merged at this point
157 33
            $cell->applyStyle($row->getStyle());
158 33
            $this->styleHelper->applyExtraStylesIfNeeded($cell);
159 33
            $registeredStyle = $this->styleHelper->registerStyle($cell->getStyle());
160 33
            $rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cell, $registeredStyle->getId());
161 31
            $cellNumber++;
162
        }
163
164 31
        $rowXML .= '</row>';
165
166 31
        $wasWriteSuccessful = fwrite($worksheet->getFilePointer(), $rowXML);
167 31
        if ($wasWriteSuccessful === false) {
168
            throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
169
        }
170 31
    }
171
172
    /**
173
     * Build and return xml for a single cell.
174
     *
175
     * @param int $rowIndex
176
     * @param int $cellNumber
177
     * @param Cell $cell
178
     * @param int $styleId
179
     * @return string
180
     * @throws InvalidArgumentException If the given value cannot be processed
181
     */
182 33
    private function getCellXML($rowIndex, $cellNumber, Cell $cell, $styleId)
183
    {
184 33
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
185 33
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
186 33
        $cellXML .= ' s="' . $styleId . '"';
187
188 33
        if ($cell->isString()) {
189 32
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue());
190 5
        } else if ($cell->isBoolean()) {
191 2
            $cellXML .= ' t="b"><v>' . intval($cell->getValue()) . '</v></c>';
192 5
        } else if ($cell->isNumeric()) {
193 2
            $cellXML .= '><v>' . $cell->getValue() . '</v></c>';
194 4
        } else if ($cell->isEmpty()) {
195 2
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
196 1
                $cellXML .= '/>';
197
            } else {
198
                // don't write empty cells that do no need styling
199
                // NOTE: not appending to $cellXML is the right behavior!!
200 2
                $cellXML = '';
201
            }
202
        } else {
203 2
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cell->getValue()));
204
        }
205
206 31
        return $cellXML;
207
    }
208
209
    /**
210
     * Returns the XML fragment for a cell containing a non empty string
211
     *
212
     * @param string $cellValue The cell value
213
     * @return string The XML fragment representing the cell
214
     * @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
215
     */
216 32
    private function getCellXMLFragmentForNonEmptyString($cellValue)
217
    {
218 32
        if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
219 1
            throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
220
        }
221
222 31
        if ($this->shouldUseInlineStrings) {
223 26
            $cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
224
        } else {
225 5
            $sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
226 5
            $cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
227
        }
228
229 31
        return $cellXMLFragment;
230
    }
231
232
    /**
233
     * Closes the worksheet
234
     *
235
     * @param Worksheet $worksheet
236
     * @return void
237
     */
238 36
    public function close(Worksheet $worksheet)
239
    {
240 36
        $worksheetFilePointer = $worksheet->getFilePointer();
241
242 36
        if (!is_resource($worksheetFilePointer)) {
243
            return;
244
        }
245
246 36
        fwrite($worksheetFilePointer, '</sheetData>');
247 36
        fwrite($worksheetFilePointer, '</worksheet>');
248 36
        fclose($worksheetFilePointer);
249
    }
250
}