This repository was archived by the owner on May 26, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 639
/
Copy pathWorksheetManager.php
302 lines (260 loc) · 11.2 KB
/
WorksheetManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
namespace Box\Spout\Writer\XLSX\Manager;
use Box\Spout\Common\Entity\Cell;
use Box\Spout\Common\Entity\Row;
use Box\Spout\Common\Entity\Style\Style;
use Box\Spout\Common\Exception\InvalidArgumentException;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Helper\Escaper\XLSX as XLSXEscaper;
use Box\Spout\Common\Helper\StringHelper;
use Box\Spout\Common\Manager\OptionsManagerInterface;
use Box\Spout\Writer\Common\Creator\InternalEntityFactory;
use Box\Spout\Writer\Common\Entity\Options;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Common\Helper\CellHelper;
use Box\Spout\Writer\Common\Manager\RegisteredStyle;
use Box\Spout\Writer\Common\Manager\RowManager;
use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
use Box\Spout\Writer\XLSX\Manager\Style\StyleManager;
/**
* Class WorksheetManager
* XLSX worksheet manager, providing the interfaces to work with XLSX worksheets.
*/
class WorksheetManager implements WorksheetManagerInterface
{
/**
* Maximum number of characters a cell can contain
* @see https://support.office.com/en-us/article/Excel-specifications-and-limits-16c69c74-3d6a-4aaf-ba35-e6eb276e8eaa [Excel 2007]
* @see https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 [Excel 2010]
* @see https://support.office.com/en-us/article/Excel-specifications-and-limits-ca36e2dc-1f09-4620-b726-67c00b05040f [Excel 2013/2016]
*/
const MAX_CHARACTERS_PER_CELL = 32767;
const SHEET_XML_FILE_HEADER = <<<'EOD'
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
EOD;
/** @var bool Whether inline or shared strings should be used */
protected $shouldUseInlineStrings;
/** @var RowManager Manages rows */
private $rowManager;
/** @var StyleManager Manages styles */
private $styleManager;
/** @var StyleMerger Helper to merge styles together */
private $styleMerger;
/** @var SharedStringsManager Helper to write shared strings */
private $sharedStringsManager;
/** @var XLSXEscaper Strings escaper */
private $stringsEscaper;
/** @var StringHelper String helper */
private $stringHelper;
/** @var InternalEntityFactory Factory to create entities */
private $entityFactory;
/**
* WorksheetManager constructor.
*
* @param OptionsManagerInterface $optionsManager
* @param RowManager $rowManager
* @param StyleManager $styleManager
* @param StyleMerger $styleMerger
* @param SharedStringsManager $sharedStringsManager
* @param XLSXEscaper $stringsEscaper
* @param StringHelper $stringHelper
* @param InternalEntityFactory $entityFactory
*/
public function __construct(
OptionsManagerInterface $optionsManager,
RowManager $rowManager,
StyleManager $styleManager,
StyleMerger $styleMerger,
SharedStringsManager $sharedStringsManager,
XLSXEscaper $stringsEscaper,
StringHelper $stringHelper,
InternalEntityFactory $entityFactory
) {
$this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS);
$this->rowManager = $rowManager;
$this->styleManager = $styleManager;
$this->styleMerger = $styleMerger;
$this->sharedStringsManager = $sharedStringsManager;
$this->stringsEscaper = $stringsEscaper;
$this->stringHelper = $stringHelper;
$this->entityFactory = $entityFactory;
}
/**
* @return SharedStringsManager
*/
public function getSharedStringsManager()
{
return $this->sharedStringsManager;
}
/**
* {@inheritdoc}
*/
public function startSheet(Worksheet $worksheet)
{
$sheetFilePointer = \fopen($worksheet->getFilePath(), 'w');
$this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
$worksheet->setFilePointer($sheetFilePointer);
\fwrite($sheetFilePointer, self::SHEET_XML_FILE_HEADER);
\fwrite($sheetFilePointer, '<sheetData>');
}
/**
* Checks if the sheet has been sucessfully created. Throws an exception if not.
*
* @param bool|resource $sheetFilePointer Pointer to the sheet data file or FALSE if unable to open the file
* @throws IOException If the sheet data file cannot be opened for writing
* @return void
*/
private function throwIfSheetFilePointerIsNotAvailable($sheetFilePointer)
{
if (!$sheetFilePointer) {
throw new IOException('Unable to open sheet for writing.');
}
}
/**
* {@inheritdoc}
*/
public function addRow(Worksheet $worksheet, Row $row)
{
if (!$this->rowManager->isEmpty($row)) {
$this->addNonEmptyRow($worksheet, $row);
}
$worksheet->setLastWrittenRowIndex($worksheet->getLastWrittenRowIndex() + 1);
}
/**
* Adds non empty row to the worksheet.
*
* @param Worksheet $worksheet The worksheet to add the row to
* @param Row $row The row to be written
* @throws IOException If the data cannot be written
* @throws InvalidArgumentException If a cell value's type is not supported
* @return void
*/
private function addNonEmptyRow(Worksheet $worksheet, Row $row)
{
$rowStyle = $row->getStyle();
$rowIndexOneBased = $worksheet->getLastWrittenRowIndex() + 1;
$numCells = $row->getNumCells();
$rowXML = '<row r="' . $rowIndexOneBased . '" spans="1:' . $numCells . '">';
foreach ($row->getCells() as $columnIndexZeroBased => $cell) {
$registeredStyle = $this->applyStyleAndRegister($cell, $rowStyle);
$cellStyle = $registeredStyle->getStyle();
if ($registeredStyle->isMatchingRowStyle()) {
$rowStyle = $cellStyle; // Replace actual rowStyle (possibly with null id) by registered style (with id)
}
$rowXML .= $this->getCellXML($rowIndexOneBased, $columnIndexZeroBased, $cell, $cellStyle->getId());
}
$rowXML .= '</row>';
$wasWriteSuccessful = \fwrite($worksheet->getFilePointer(), $rowXML);
if ($wasWriteSuccessful === false) {
throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
}
}
/**
* Applies styles to the given style, merging the cell's style with its row's style
*
* @param Cell $cell
* @param Style $rowStyle
*
* @throws InvalidArgumentException If the given value cannot be processed
* @return RegisteredStyle
*/
private function applyStyleAndRegister(Cell $cell, Style $rowStyle) : RegisteredStyle
{
$isMatchingRowStyle = false;
if ($cell->getStyle()->isEmpty()) {
$cell->setStyle($rowStyle);
$possiblyUpdatedStyle = $this->styleManager->applyExtraStylesIfNeeded($cell);
if ($possiblyUpdatedStyle->isUpdated()) {
$registeredStyle = $this->styleManager->registerStyle($possiblyUpdatedStyle->getStyle());
} else {
$registeredStyle = $this->styleManager->registerStyle($rowStyle);
$isMatchingRowStyle = true;
}
} else {
$mergedCellAndRowStyle = $this->styleMerger->merge($cell->getStyle(), $rowStyle);
$cell->setStyle($mergedCellAndRowStyle);
$possiblyUpdatedStyle = $this->styleManager->applyExtraStylesIfNeeded($cell);
if ($possiblyUpdatedStyle->isUpdated()) {
$newCellStyle = $possiblyUpdatedStyle->getStyle();
} else {
$newCellStyle = $mergedCellAndRowStyle;
}
$registeredStyle = $this->styleManager->registerStyle($newCellStyle);
}
return new RegisteredStyle($registeredStyle, $isMatchingRowStyle);
}
/**
* Builds and returns xml for a single cell.
*
* @param int $rowIndexOneBased
* @param int $columnIndexZeroBased
* @param Cell $cell
* @param int $styleId
*
* @throws InvalidArgumentException If the given value cannot be processed
* @return string
*/
private function getCellXML($rowIndexOneBased, $columnIndexZeroBased, Cell $cell, $styleId)
{
$columnLetters = CellHelper::getColumnLettersFromColumnIndex($columnIndexZeroBased);
$cellXML = '<c r="' . $columnLetters . $rowIndexOneBased . '"';
$cellXML .= ' s="' . $styleId . '"';
if ($cell->isString()) {
$cellXML .= $this->getCellXMLFragmentForNonEmptyString($cell->getValue());
} elseif ($cell->isBoolean()) {
$cellXML .= ' t="b"><v>' . (int) ($cell->getValue()) . '</v></c>';
} elseif ($cell->isNumeric()) {
$cellXML .= '><v>' . $this->stringHelper->formatNumericValue($cell->getValue()) . '</v></c>';
} elseif ($cell->isError() && is_string($cell->getValueEvenIfError())) {
// only writes the error value if it's a string
$cellXML .= ' t="e"><v>' . $cell->getValueEvenIfError() . '</v></c>';
} elseif ($cell->isEmpty()) {
if ($this->styleManager->shouldApplyStyleOnEmptyCell($styleId)) {
$cellXML .= '/>';
} else {
// don't write empty cells that do no need styling
// NOTE: not appending to $cellXML is the right behavior!!
$cellXML = '';
}
} else {
$value = $cell->getValueEvenIfError();
throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . (\is_object($value) ? \get_class($value) : \gettype($value)));
}
return $cellXML;
}
/**
* Returns the XML fragment for a cell containing a non empty string
*
* @param string $cellValue The cell value
* @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
* @return string The XML fragment representing the cell
*/
private function getCellXMLFragmentForNonEmptyString($cellValue)
{
if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
}
if ($this->shouldUseInlineStrings) {
$cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
} else {
$sharedStringId = $this->sharedStringsManager->writeString($cellValue);
$cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
}
return $cellXMLFragment;
}
/**
* {@inheritdoc}
*/
public function close(Worksheet $worksheet)
{
$worksheetFilePointer = $worksheet->getFilePointer();
if (!\is_resource($worksheetFilePointer)) {
return;
}
\fwrite($worksheetFilePointer, '</sheetData>');
\fwrite($worksheetFilePointer, '</worksheet>');
\fclose($worksheetFilePointer);
}
}