Failed Conditions
Pull Request — master (#3962)
by Owen
17:41 queued 07:20
created

Content::writeCells()   F

Complexity

Conditions 21
Paths 207

Size

Total Lines 111
Code Lines 85

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 74
CRAP Score 21.008

Importance

Changes 0
Metric Value
eloc 85
dl 0
loc 111
ccs 74
cts 76
cp 0.9737
rs 3.2458
c 0
b 0
f 0
cc 21
nc 207
nop 2
crap 21.008

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
7
use PhpOffice\PhpSpreadsheet\Cell\Cell;
8
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
9
use PhpOffice\PhpSpreadsheet\Cell\DataType;
10
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
11
use PhpOffice\PhpSpreadsheet\Spreadsheet;
12
use PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator;
13
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
14
use PhpOffice\PhpSpreadsheet\Writer\Ods;
15
use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment;
16
use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Style;
17
18
/**
19
 * @author     Alexander Pervakov <[email protected]>
20
 */
21
class Content extends WriterPart
22
{
23
    const NUMBER_COLS_REPEATED_MAX = 1024;
24
    const NUMBER_ROWS_REPEATED_MAX = 1048576;
25
26
    private Formula $formulaConvertor;
27
28
    /**
29
     * Set parent Ods writer.
30
     */
31 36
    public function __construct(Ods $writer)
32
    {
33 36
        parent::__construct($writer);
34
35 36
        $this->formulaConvertor = new Formula($this->getParentWriter()->getSpreadsheet()->getDefinedNames());
36
    }
37
38
    /**
39
     * Write content.xml to XML format.
40
     *
41
     * @return string XML Output
42
     */
43 35
    public function write(): string
44
    {
45 35
        $objWriter = null;
46 35
        if ($this->getParentWriter()->getUseDiskCaching()) {
47
            $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
48
        } else {
49 35
            $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
50
        }
51
52
        // XML header
53 35
        $objWriter->startDocument('1.0', 'UTF-8');
54
55
        // Content
56 35
        $objWriter->startElement('office:document-content');
57 35
        $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
58 35
        $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0');
59 35
        $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0');
60 35
        $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0');
61 35
        $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0');
62 35
        $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0');
63 35
        $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
64 35
        $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
65 35
        $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0');
66 35
        $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0');
67 35
        $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0');
68 35
        $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0');
69 35
        $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0');
70 35
        $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0');
71 35
        $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML');
72 35
        $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0');
73 35
        $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0');
74 35
        $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
75 35
        $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer');
76 35
        $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc');
77 35
        $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events');
78 35
        $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms');
79 35
        $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
80 35
        $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
81 35
        $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report');
82 35
        $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2');
83 35
        $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
84 35
        $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#');
85 35
        $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table');
86 35
        $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0');
87 35
        $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0');
88 35
        $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/');
89 35
        $objWriter->writeAttribute('office:version', '1.2');
90
91 35
        $objWriter->writeElement('office:scripts');
92 35
        $objWriter->writeElement('office:font-face-decls');
93
94
        // Styles XF
95 35
        $objWriter->startElement('office:automatic-styles');
96 35
        $this->writeXfStyles($objWriter, $this->getParentWriter()->getSpreadsheet());
97 35
        $objWriter->endElement();
98
99 35
        $objWriter->startElement('office:body');
100 35
        $objWriter->startElement('office:spreadsheet');
101 35
        $objWriter->writeElement('table:calculation-settings');
102
103 35
        $this->writeSheets($objWriter);
104
105 35
        (new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write();
106
        // Defined names (ranges and formulae)
107 35
        (new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write();
108
109 35
        $objWriter->endElement();
110 35
        $objWriter->endElement();
111 35
        $objWriter->endElement();
112
113 35
        return $objWriter->getData();
114
    }
115
116
    /**
117
     * Write sheets.
118
     */
119 35
    private function writeSheets(XMLWriter $objWriter): void
120
    {
121 35
        $spreadsheet = $this->getParentWriter()->getSpreadsheet();
122 35
        $sheetCount = $spreadsheet->getSheetCount();
123 35
        for ($sheetIndex = 0; $sheetIndex < $sheetCount; ++$sheetIndex) {
124 35
            $spreadsheet->getSheet($sheetIndex)->calculateArrays($this->getParentWriter()->getPreCalculateFormulas());
125 35
            $objWriter->startElement('table:table');
126 35
            $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($sheetIndex)->getTitle());
127 35
            $objWriter->writeAttribute('table:style-name', Style::TABLE_STYLE_PREFIX . (string) ($sheetIndex + 1));
128 35
            $objWriter->writeElement('office:forms');
129 35
            $lastColumn = 0;
130 35
            foreach ($spreadsheet->getSheet($sheetIndex)->getColumnDimensions() as $columnDimension) {
131 5
                $thisColumn = $columnDimension->getColumnNumeric();
132 5
                $emptyColumns = $thisColumn - $lastColumn - 1;
133 5
                if ($emptyColumns > 0) {
134 4
                    $objWriter->startElement('table:table-column');
135 4
                    $objWriter->writeAttribute('table:number-columns-repeated', (string) $emptyColumns);
136 4
                    $objWriter->endElement();
137
                }
138 5
                $lastColumn = $thisColumn;
139 5
                $objWriter->startElement('table:table-column');
140 5
                $objWriter->writeAttribute(
141 5
                    'table:style-name',
142 5
                    sprintf('%s_%d_%d', Style::COLUMN_STYLE_PREFIX, $sheetIndex, $columnDimension->getColumnNumeric())
143 5
                );
144 5
                $objWriter->writeAttribute('table:default-cell-style-name', 'ce0');
145
//                $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX);
146 5
                $objWriter->endElement();
147
            }
148 35
            $this->writeRows($objWriter, $spreadsheet->getSheet($sheetIndex), $sheetIndex);
149 35
            $objWriter->endElement();
150
        }
151
    }
152
153
    /**
154
     * Write rows of the specified sheet.
155
     */
156 35
    private function writeRows(XMLWriter $objWriter, Worksheet $sheet, int $sheetIndex): void
157
    {
158 35
        $numberRowsRepeated = self::NUMBER_ROWS_REPEATED_MAX;
159 35
        $span_row = 0;
160 35
        $rows = $sheet->getRowIterator();
161 35
        foreach ($rows as $row) {
162 35
            $cellIterator = $row->getCellIterator();
163 35
            --$numberRowsRepeated;
164 35
            if ($cellIterator->valid()) {
165 35
                $objWriter->startElement('table:table-row');
166 35
                if ($span_row) {
167
                    if ($span_row > 1) {
168
                        $objWriter->writeAttribute('table:number-rows-repeated', (string) $span_row);
169
                    }
170
                    $objWriter->startElement('table:table-cell');
171
                    $objWriter->writeAttribute('table:number-columns-repeated', (string) self::NUMBER_COLS_REPEATED_MAX);
172
                    $objWriter->endElement();
173
                    $span_row = 0;
174
                } else {
175 35
                    if ($sheet->rowDimensionExists($row->getRowIndex()) && $sheet->getRowDimension($row->getRowIndex())->getRowHeight() > 0) {
176
                        $objWriter->writeAttribute(
177
                            'table:style-name',
178
                            sprintf('%s_%d_%d', Style::ROW_STYLE_PREFIX, $sheetIndex, $row->getRowIndex())
179
                        );
180
                    }
181 35
                    $this->writeCells($objWriter, $cellIterator);
182
                }
183 35
                $objWriter->endElement();
184
            } else {
185
                ++$span_row;
186
            }
187
        }
188
    }
189
190
    /**
191
     * Write cells of the specified row.
192
     */
193 35
    private function writeCells(XMLWriter $objWriter, RowCellIterator $cells): void
194
    {
195 35
        $numberColsRepeated = self::NUMBER_COLS_REPEATED_MAX;
196 35
        $prevColumn = -1;
197 35
        foreach ($cells as $cell) {
198
            /** @var Cell $cell */
199 35
            $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1;
200 35
            $attributes = $cell->getFormulaAttributes() ?? [];
201
202 35
            $this->writeCellSpan($objWriter, $column, $prevColumn);
203 35
            $objWriter->startElement('table:table-cell');
204 35
            $this->writeCellMerge($objWriter, $cell);
205
206
            // Style XF
207 35
            $style = $cell->getXfIndex();
208 35
            if ($style !== null) {
209 35
                $objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style);
210
            }
211
212 35
            switch ($cell->getDataType()) {
213
                case DataType::TYPE_BOOL:
214 3
                    $objWriter->writeAttribute('office:value-type', 'boolean');
215 3
                    $objWriter->writeAttribute('office:boolean-value', $cell->getValue() ? 'true' : 'false');
216 3
                    $objWriter->writeElement('text:p', Calculation::getInstance()->getLocaleBoolean($cell->getValue() ? 'TRUE' : 'FALSE'));
217
218 3
                    break;
219
                case DataType::TYPE_ERROR:
220 1
                    $objWriter->writeAttribute('table:formula', 'of:=#NULL!');
221 1
                    $objWriter->writeAttribute('office:value-type', 'string');
222 1
                    $objWriter->writeAttribute('office:string-value', '');
223 1
                    $objWriter->writeElement('text:p', '#NULL!');
224
225 1
                    break;
226
                case DataType::TYPE_FORMULA:
227 9
                    $formulaValue = $cell->getValueString();
228 9
                    if ($this->getParentWriter()->getPreCalculateFormulas()) {
229
                        try {
230 8
                            $formulaValue = $cell->getCalculatedValueString();
231
                        } catch (CalculationException $e) {
232
                            // don't do anything
233
                        }
234
                    }
235 9
                    if (isset($attributes['ref'])) {
236 3
                        if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', (string) $attributes['ref'], $matches) == 1) {
237 3
                            $matrixRowSpan = 1;
238 3
                            $matrixColSpan = 1;
239 3
                            if (isset($matches[3])) {
240 3
                                $minRow = (int) $matches[2];
241 3
                                $maxRow = (int) $matches[5];
242 3
                                $matrixRowSpan = $maxRow - $minRow + 1;
243 3
                                $minCol = Coordinate::columnIndexFromString($matches[1]);
244 3
                                $maxCol = Coordinate::columnIndexFromString($matches[4]);
245 3
                                $matrixColSpan = $maxCol - $minCol + 1;
246
                            }
247 3
                            $objWriter->writeAttribute('table:number-matrix-columns-spanned', "$matrixColSpan");
248 3
                            $objWriter->writeAttribute('table:number-matrix-rows-spanned', "$matrixRowSpan");
249
                        }
250
                    }
251 9
                    $objWriter->writeAttribute('table:formula', $this->formulaConvertor->convertFormula($cell->getValueString()));
252 9
                    if (is_numeric($formulaValue)) {
253 6
                        $objWriter->writeAttribute('office:value-type', 'float');
254
                    } else {
255 3
                        $objWriter->writeAttribute('office:value-type', 'string');
256
                    }
257 9
                    $objWriter->writeAttribute('office:value', $formulaValue);
258 9
                    $objWriter->writeElement('text:p', $formulaValue);
259
260 9
                    break;
261
                case DataType::TYPE_NUMERIC:
262 16
                    $objWriter->writeAttribute('office:value-type', 'float');
263 16
                    $objWriter->writeAttribute('office:value', $cell->getValueString());
264 16
                    $objWriter->writeElement('text:p', $cell->getValueString());
265
266 16
                    break;
267
                case DataType::TYPE_INLINE:
268
                    // break intentionally omitted
269
                case DataType::TYPE_STRING:
270 19
                    $objWriter->writeAttribute('office:value-type', 'string');
271 19
                    $url = $cell->getHyperlink()->getUrl();
272 19
                    if (empty($url)) {
273 19
                        $objWriter->writeElement('text:p', $cell->getValueString());
274
                    } else {
275 1
                        $objWriter->startElement('text:p');
276 1
                        $objWriter->startElement('text:a');
277 1
                        $sheets = 'sheet://';
278 1
                        $lensheets = strlen($sheets);
279 1
                        if (substr($url, 0, $lensheets) === $sheets) {
280 1
                            $url = '#' . substr($url, $lensheets);
281
                        }
282 1
                        $objWriter->writeAttribute('xlink:href', $url);
283 1
                        $objWriter->writeAttribute('xlink:type', 'simple');
284 1
                        $objWriter->text($cell->getValueString());
285 1
                        $objWriter->endElement(); // text:a
286 1
                        $objWriter->endElement(); // text:p
287
                    }
288
289 19
                    break;
290
            }
291 35
            Comment::write($objWriter, $cell);
292 35
            $objWriter->endElement();
293 35
            $prevColumn = $column;
294
        }
295
296 35
        $numberColsRepeated = $numberColsRepeated - $prevColumn - 1;
297 35
        if ($numberColsRepeated > 0) {
298 35
            if ($numberColsRepeated > 1) {
299 35
                $objWriter->startElement('table:table-cell');
300 35
                $objWriter->writeAttribute('table:number-columns-repeated', (string) $numberColsRepeated);
301 35
                $objWriter->endElement();
302
            } else {
303
                $objWriter->writeElement('table:table-cell');
304
            }
305
        }
306
    }
307
308
    /**
309
     * Write span.
310
     */
311 35
    private function writeCellSpan(XMLWriter $objWriter, int $curColumn, int $prevColumn): void
312
    {
313 35
        $diff = $curColumn - $prevColumn - 1;
314 35
        if (1 === $diff) {
315
            $objWriter->writeElement('table:table-cell');
316 35
        } elseif ($diff > 1) {
317
            $objWriter->startElement('table:table-cell');
318
            $objWriter->writeAttribute('table:number-columns-repeated', (string) $diff);
319
            $objWriter->endElement();
320
        }
321
    }
322
323
    /**
324
     * Write XF cell styles.
325
     */
326 35
    private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void
327
    {
328 35
        $styleWriter = new Style($writer);
329
330 35
        $sheetCount = $spreadsheet->getSheetCount();
331 35
        for ($i = 0; $i < $sheetCount; ++$i) {
332 35
            $worksheet = $spreadsheet->getSheet($i);
333 35
            $styleWriter->writeTableStyle($worksheet, $i + 1);
334
335 35
            $worksheet->calculateColumnWidths();
336 35
            foreach ($worksheet->getColumnDimensions() as $columnDimension) {
337 5
                if ($columnDimension->getWidth() !== -1.0) {
338 5
                    $styleWriter->writeColumnStyles($columnDimension, $i);
339
                }
340
            }
341
        }
342 35
        for ($i = 0; $i < $sheetCount; ++$i) {
343 35
            $worksheet = $spreadsheet->getSheet($i);
344 35
            foreach ($worksheet->getRowDimensions() as $rowDimension) {
345 2
                if ($rowDimension->getRowHeight() > 0.0) {
346
                    $styleWriter->writeRowStyles($rowDimension, $i);
347
                }
348
            }
349
        }
350
351 35
        foreach ($spreadsheet->getCellXfCollection() as $style) {
352 35
            $styleWriter->write($style);
353
        }
354
    }
355
356
    /**
357
     * Write attributes for merged cell.
358
     */
359 35
    private function writeCellMerge(XMLWriter $objWriter, Cell $cell): void
360
    {
361 35
        if (!$cell->isMergeRangeValueCell()) {
362 35
            return;
363
        }
364
365 2
        $mergeRange = Coordinate::splitRange((string) $cell->getMergeRange());
366 2
        [$startCell, $endCell] = $mergeRange[0];
367 2
        $start = Coordinate::coordinateFromString($startCell);
368 2
        $end = Coordinate::coordinateFromString($endCell);
369 2
        $columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1;
370 2
        $rowSpan = ((int) $end[1]) - ((int) $start[1]) + 1;
371
372 2
        $objWriter->writeAttribute('table:number-columns-spanned', (string) $columnSpan);
373 2
        $objWriter->writeAttribute('table:number-rows-spanned', (string) $rowSpan);
374
    }
375
}
376