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
338 lines (288 loc) · 12.8 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
<?php
namespace Box\Spout\Writer\ODS\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\ODS as ODSEscaper;
use Box\Spout\Common\Helper\StringHelper;
use Box\Spout\Common\Manager\OptionsManagerInterface;
use Box\Spout\Writer\Common\Helper\AppendHelper;
use Box\Spout\Writer\Common\Entity\Options;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Common\Manager\RegisteredStyle;
use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
use Box\Spout\Writer\ODS\Manager\Style\StyleManager;
/**
* Class WorksheetManager
* ODS worksheet manager, providing the interfaces to work with ODS worksheets.
*/
class WorksheetManager implements WorksheetManagerInterface
{
/** @var \Box\Spout\Common\Helper\Escaper\ODS Strings escaper */
private $stringsEscaper;
/** @var StringHelper String helper */
private $stringHelper;
/** @var StyleManager Manages styles */
private $styleManager;
/** @var StyleMerger Helper to merge styles together */
private $styleMerger;
/** $int file pointer head position */
private $headWritePosition;
/** @var int Width calculation style */
protected $widthCalcuationStyle;
/** @var int Fixed Width */
protected $fixedWidth;
/**
* WorksheetManager constructor.
*
* @param OptionsManagerInterface $optionsManager
* @param StyleManager $styleManager
* @param StyleMerger $styleMerger
* @param ODSEscaper $stringsEscaper
* @param StringHelper $stringHelper
*/
public function __construct(
OptionsManagerInterface $optionsManager,
StyleManager $styleManager,
StyleMerger $styleMerger,
ODSEscaper $stringsEscaper,
StringHelper $stringHelper
) {
$this->widthCalcuationStyle = $optionsManager->getOption(Options::ROWWIDTH_CALC_STYLE);
$this->fixedWidth = $optionsManager->getOption(Options::ROWWIDTH_FIXED);
$this->styleManager = $styleManager;
$this->styleMerger = $styleMerger;
$this->stringsEscaper = $stringsEscaper;
$this->stringHelper = $stringHelper;
}
/**
* Prepares the worksheet to accept data
*
* @param Worksheet $worksheet The worksheet to start
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
* @return void
*/
public function startSheet(Worksheet $worksheet)
{
$sheetFilePointer = \fopen($worksheet->getFilePath(), 'w+');
$this->throwIfSheetFilePointerIsNotAvailable($sheetFilePointer);
$worksheet->setWidthCalculation($this->widthCalcuationStyle);
$worksheet->setFixedSheetWidth($this->fixedWidth);
if ($worksheet->getWidthCalculation() != Worksheet::W_NONE) {
$this->headWritePosition = ftell($sheetFilePointer);
}
$worksheet->setFilePointer($sheetFilePointer);
}
/**
* 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.');
}
}
/**
* Returns the table XML root node as string.
*
* @param Worksheet $worksheet
* @return string "<table>" node as string
*/
public function getTableElementStartAsString(Worksheet $worksheet)
{
$externalSheet = $worksheet->getExternalSheet();
$escapedSheetName = $this->stringsEscaper->escape($externalSheet->getName());
$tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
$tableElement = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
if ($worksheet->getWidthCalculation() != Worksheet::W_NONE) {
foreach ($worksheet->getColumnWidths() as $i => $w){
$colNo = $i + 1;
$tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co'.$colNo.'"/>';
}
} else {
$tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
}
return $tableElement;
}
/**
* Adds a row to the given worksheet.
*
* @param Worksheet $worksheet The worksheet to add the row to
* @param Row $row The row to be added
* @throws InvalidArgumentException If a cell value's type is not supported
* @throws IOException If the data cannot be written
* @return void
*/
public function addRow(Worksheet $worksheet, Row $row)
{
$cells = $row->getCells();
$rowStyle = $row->getStyle();
$data = '<table:table-row table:style-name="ro1">';
$currentCellIndex = 0;
$nextCellIndex = 1;
for ($i = 0; $i < $row->getNumCells(); $i++) {
/** @var Cell $cell */
$cell = $cells[$currentCellIndex];
/** @var Cell|null $nextCell */
$nextCell = isset($cells[$nextCellIndex]) ? $cells[$nextCellIndex] : null;
if ($worksheet->getWidthCalculation() != Worksheet::W_NONE) {
$worksheet->autoSetWidth($cell, $rowStyle, $i);
}
if ($nextCell === null || $cell->getValue() !== $nextCell->getValue()) {
$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)
}
$data .= $this->getCellXMLWithStyle($cell, $cellStyle, $currentCellIndex, $nextCellIndex);
$currentCellIndex = $nextCellIndex;
}
$nextCellIndex++;
}
$data .= '</table:table-row>';
$wasWriteSuccessful = \fwrite($worksheet->getFilePointer(), $data);
if ($wasWriteSuccessful === false) {
throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
}
// only update the count if the write worked
$lastWrittenRowIndex = $worksheet->getLastWrittenRowIndex();
$worksheet->setLastWrittenRowIndex($lastWrittenRowIndex + 1);
}
/**
* 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 a cell value's type is not supported
* @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);
}
private function getCellXMLWithStyle(Cell $cell, Style $style, int $currentCellIndex, int $nextCellIndex) : string
{
$styleIndex = $style->getId() + 1; // 1-based
$numTimesValueRepeated = ($nextCellIndex - $currentCellIndex);
return $this->getCellXML($cell, $styleIndex, $numTimesValueRepeated);
}
/**
* Returns the cell XML content, given its value.
*
* @param Cell $cell The cell to be written
* @param int $styleIndex Index of the used style
* @param int $numTimesValueRepeated Number of times the value is consecutively repeated
* @throws InvalidArgumentException If a cell value's type is not supported
* @return string The cell XML content
*/
private function getCellXML(Cell $cell, $styleIndex, $numTimesValueRepeated)
{
$data = '<table:table-cell table:style-name="ce' . $styleIndex . '"';
if ($numTimesValueRepeated !== 1) {
$data .= ' table:number-columns-repeated="' . $numTimesValueRepeated . '"';
}
if ($cell->isString()) {
$data .= ' office:value-type="string" calcext:value-type="string">';
$cellValueLines = \explode("\n", $cell->getValue());
foreach ($cellValueLines as $cellValueLine) {
$data .= '<text:p>' . $this->stringsEscaper->escape($cellValueLine) . '</text:p>';
}
$data .= '</table:table-cell>';
} elseif ($cell->isBoolean()) {
$value = $cell->getValue() ? 'true' : 'false'; // boolean-value spec: http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#datatype-boolean
$data .= ' office:value-type="boolean" calcext:value-type="boolean" office:boolean-value="' . $value . '">';
$data .= '<text:p>' . $cell->getValue() . '</text:p>';
$data .= '</table:table-cell>';
} elseif ($cell->isNumeric()) {
$cellValue = $this->stringHelper->formatNumericValue($cell->getValue());
$data .= ' office:value-type="float" calcext:value-type="float" office:value="' . $cellValue . '">';
$data .= '<text:p>' . $cellValue . '</text:p>';
$data .= '</table:table-cell>';
} elseif ($cell->isError() && is_string($cell->getValueEvenIfError())) {
// only writes the error value if it's a string
$data .= ' office:value-type="string" calcext:value-type="error" office:value="">';
$data .= '<text:p>' . $cell->getValueEvenIfError() . '</text:p>';
$data .= '</table:table-cell>';
} elseif ($cell->isEmpty()) {
$data .= '/>';
} else {
throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . \gettype($cell->getValue()));
}
return $data;
}
/**
* Generate the related column widths style xml to be inserted in content.xml
* @param Worksheet $worksheet
* @return string
*/
public function getWidthStylesContent($worksheet)
{
if ($worksheet->getWidthCalculation() != Worksheet::W_NONE) {
//create the col styles
$style = '';
$widths = $worksheet->getColumnWidths();
//todo: this may not be adequate for multiple worksheets
//re-calculate width for fixed sets
if ($worksheet->getWidthCalculation() == Worksheet::W_FIXED) {
$total = array_sum($widths);
foreach($widths as $i => $w) {
$wr = ($w / $total) * $worksheet->getFixedSheetWidth();
$widths[$i] = $wr;
}
}
foreach ($widths as $i => $width){
//this is a rough equivalent based on pixel density,
$win = round($width / 9.6, 2);//convert to inches
$colNo = $i + 1;
$style .= '<style:style style:name="co'.$colNo.
'" style:family="table-column"><style:table-column-properties fo:break-before="auto" style:column-width="'.
$win.
'in"/></style:style>';
}
return $style;
}
return "";
}
/**
* Closes the worksheet
*
* @param Worksheet $worksheet
* @return void
*/
public function close(Worksheet $worksheet)
{
$worksheetFilePointer = $worksheet->getFilePointer();
if (!\is_resource($worksheetFilePointer)) {
return;
}
\fclose($worksheetFilePointer);
}
}