Passed
Pull Request — master (#4508)
by Owen
11:14
created

Xlsx::createStyleDictionaries()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 30
rs 9.6666
ccs 16
cts 16
cp 1
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
7
use PhpOffice\PhpSpreadsheet\HashTable;
8
use PhpOffice\PhpSpreadsheet\Spreadsheet;
9
use PhpOffice\PhpSpreadsheet\Style\Borders;
10
use PhpOffice\PhpSpreadsheet\Style\Conditional;
11
use PhpOffice\PhpSpreadsheet\Style\Fill;
12
use PhpOffice\PhpSpreadsheet\Style\Font;
13
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
14
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
15
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing;
16
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
17
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
18
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart;
19
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments;
20
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes;
21
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps;
22
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing;
23
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels;
24
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon;
25
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA;
26
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable;
27
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style;
28
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Table;
29
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme;
30
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook;
31
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet;
32
use ZipArchive;
33
use ZipStream\Exception\OverflowException;
34
use ZipStream\ZipStream;
35
36
class Xlsx extends BaseWriter
37
{
38
    /**
39
     * Office2003 compatibility.
40
     */
41
    private bool $office2003compatibility = false;
42
43
    /**
44
     * Private Spreadsheet.
45
     */
46
    private Spreadsheet $spreadSheet;
47
48
    /**
49
     * Private string table.
50
     *
51
     * @var string[]
52
     */
53
    private array $stringTable = [];
54
55
    /**
56
     * Private unique Conditional HashTable.
57
     *
58
     * @var HashTable<Conditional>
59
     */
60
    private HashTable $stylesConditionalHashTable;
61
62
    /**
63
     * Private unique Style HashTable.
64
     *
65
     * @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style>
66
     */
67
    private HashTable $styleHashTable;
68
69
    /**
70
     * Private unique Fill HashTable.
71
     *
72
     * @var HashTable<Fill>
73
     */
74
    private HashTable $fillHashTable;
75
76
    /**
77
     * Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
78
     *
79
     * @var HashTable<Font>
80
     */
81
    private HashTable $fontHashTable;
82
83
    /**
84
     * Private unique Borders HashTable.
85
     *
86
     * @var HashTable<Borders>
87
     */
88
    private HashTable $bordersHashTable;
89
90
    /**
91
     * Private unique NumberFormat HashTable.
92
     *
93
     * @var HashTable<NumberFormat>
94
     */
95
    private HashTable $numFmtHashTable;
96
97
    /**
98
     * Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
99
     *
100
     * @var HashTable<BaseDrawing>
101
     */
102
    private HashTable $drawingHashTable;
103
104
    /**
105
     * Private handle for zip stream.
106
     */
107
    private ZipStream $zip;
108
109
    private Chart $writerPartChart;
110
111
    private Comments $writerPartComments;
112
113
    private ContentTypes $writerPartContentTypes;
114
115
    private DocProps $writerPartDocProps;
116
117
    private Drawing $writerPartDrawing;
118
119
    private Rels $writerPartRels;
120
121
    private RelsRibbon $writerPartRelsRibbon;
122
123
    private RelsVBA $writerPartRelsVBA;
124
125
    private StringTable $writerPartStringTable;
126
127
    private Style $writerPartStyle;
128
129
    private Theme $writerPartTheme;
130
131
    private Table $writerPartTable;
132
133
    private Workbook $writerPartWorkbook;
134
135
    private Worksheet $writerPartWorksheet;
136
137
    private bool $explicitStyle0 = false;
138
139
    private bool $useCSEArrays = false;
140
141
    private bool $useDynamicArray = false;
142
143
    public const DEFAULT_FORCE_FULL_CALC = false;
144
145
    // Default changed from null in PhpSpreadsheet 4.0.0.
146
    private ?bool $forceFullCalc = self::DEFAULT_FORCE_FULL_CALC;
147
148
    /**
149
     * Create a new Xlsx Writer.
150
     */
151 441
    public function __construct(Spreadsheet $spreadsheet)
152
    {
153
        // Assign PhpSpreadsheet
154 441
        $this->setSpreadsheet($spreadsheet);
155
156 441
        $this->writerPartChart = new Chart($this);
157 441
        $this->writerPartComments = new Comments($this);
158 441
        $this->writerPartContentTypes = new ContentTypes($this);
159 441
        $this->writerPartDocProps = new DocProps($this);
160 441
        $this->writerPartDrawing = new Drawing($this);
161 441
        $this->writerPartRels = new Rels($this);
162 441
        $this->writerPartRelsRibbon = new RelsRibbon($this);
163 441
        $this->writerPartRelsVBA = new RelsVBA($this);
164 441
        $this->writerPartStringTable = new StringTable($this);
165 441
        $this->writerPartStyle = new Style($this);
166 441
        $this->writerPartTheme = new Theme($this);
167 441
        $this->writerPartTable = new Table($this);
168 441
        $this->writerPartWorkbook = new Workbook($this);
169 441
        $this->writerPartWorksheet = new Worksheet($this);
170
171
        // Set HashTable variables
172 441
        $this->bordersHashTable = new HashTable();
173 441
        $this->drawingHashTable = new HashTable();
174 441
        $this->fillHashTable = new HashTable();
175 441
        $this->fontHashTable = new HashTable();
176 441
        $this->numFmtHashTable = new HashTable();
177 441
        $this->styleHashTable = new HashTable();
178 441
        $this->stylesConditionalHashTable = new HashTable();
179 441
        $this->determineUseDynamicArrays();
180
    }
181
182 78
    public function getWriterPartChart(): Chart
183
    {
184 78
        return $this->writerPartChart;
185
    }
186
187 26
    public function getWriterPartComments(): Comments
188
    {
189 26
        return $this->writerPartComments;
190
    }
191
192 382
    public function getWriterPartContentTypes(): ContentTypes
193
    {
194 382
        return $this->writerPartContentTypes;
195
    }
196
197 382
    public function getWriterPartDocProps(): DocProps
198
    {
199 382
        return $this->writerPartDocProps;
200
    }
201
202 382
    public function getWriterPartDrawing(): Drawing
203
    {
204 382
        return $this->writerPartDrawing;
205
    }
206
207 382
    public function getWriterPartRels(): Rels
208
    {
209 382
        return $this->writerPartRels;
210
    }
211
212
    public function getWriterPartRelsRibbon(): RelsRibbon
213
    {
214
        return $this->writerPartRelsRibbon;
215
    }
216
217 2
    public function getWriterPartRelsVBA(): RelsVBA
218
    {
219 2
        return $this->writerPartRelsVBA;
220
    }
221
222 438
    public function getWriterPartStringTable(): StringTable
223
    {
224 438
        return $this->writerPartStringTable;
225
    }
226
227 383
    public function getWriterPartStyle(): Style
228
    {
229 383
        return $this->writerPartStyle;
230
    }
231
232 382
    public function getWriterPartTheme(): Theme
233
    {
234 382
        return $this->writerPartTheme;
235
    }
236
237 8
    public function getWriterPartTable(): Table
238
    {
239 8
        return $this->writerPartTable;
240
    }
241
242 382
    public function getWriterPartWorkbook(): Workbook
243
    {
244 382
        return $this->writerPartWorkbook;
245
    }
246
247 382
    public function getWriterPartWorksheet(): Worksheet
248
    {
249 382
        return $this->writerPartWorksheet;
250
    }
251
252
    public function createStyleDictionaries(): void
253
    {
254
        $this->styleHashTable->addFromSource(
255
            $this->getWriterPartStyle()->allStyles(
256
                $this->spreadSheet
257 382
            )
258
        );
259 382
        $this->stylesConditionalHashTable->addFromSource(
260 382
            $this->getWriterPartStyle()->allConditionalStyles(
261
                $this->spreadSheet
262
            )
263 382
        );
264 382
        $this->fillHashTable->addFromSource(
265
            $this->getWriterPartStyle()->allFills(
266 382
                $this->spreadSheet
267 382
            )
268 382
        );
269 382
        $this->fontHashTable->addFromSource(
270
            $this->getWriterPartStyle()->allFonts(
271
                $this->spreadSheet
272 382
            )
273 382
        );
274 382
        $this->bordersHashTable->addFromSource(
275
            $this->getWriterPartStyle()->allBorders(
276
                $this->spreadSheet
277
            )
278 382
        );
279 382
        $this->numFmtHashTable->addFromSource(
280 382
            $this->getWriterPartStyle()->allNumberFormats(
281 382
                $this->spreadSheet
282 382
            )
283 382
        );
284
    }
285
286 382
    /**
287
     * Save PhpSpreadsheet to file.
288
     *
289 382
     * @param resource|string $filename
290
     */
291 382
    public function save($filename, int $flags = 0): void
292 382
    {
293 382
        $this->processFlags($flags);
294 8
        $this->determineUseDynamicArrays();
295
296
        // garbage collect
297
        $this->pathNames = [];
298 382
        $this->spreadSheet->garbageCollect();
299 2
300 2
        $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
301
        Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
302 2
        $saveDateReturnType = Functions::getReturnDateType();
303 2
        Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
304
305
        // Create string lookup table
306 2
        $this->stringTable = [];
307 2
        for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
308
            $this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
309
        }
310
311
        // Create styles dictionaries
312 382
        $this->createStyleDictionaries();
313 2
314 2
        // Create drawing dictionary
315 2
        $this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet));
316 2
317
        /** @var string[] */
318
        $zipContent = [];
319
        // Add [Content_Types].xml to ZIP file
320
        $zipContent['[Content_Types].xml'] = $this->getWriterPartContentTypes()->writeContentTypes($this->spreadSheet, $this->includeCharts);
321
        $metadataData = (new Xlsx\Metadata($this))->writeMetadata();
322
        if ($metadataData !== '') {
323
            $zipContent['xl/metadata.xml'] = $metadataData;
324
        }
325
326
        //if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
327
        if ($this->spreadSheet->hasMacros()) {
328
            $macrosCode = $this->spreadSheet->getMacrosCode();
329
            if ($macrosCode !== null) {
330 382
                // we have the code ?
331 382
                $zipContent['xl/vbaProject.bin'] = $macrosCode; //allways in 'xl', allways named vbaProject.bin
332
                if ($this->spreadSheet->hasMacrosCertificate()) {
333
                    //signed macros ?
334 382
                    // Yes : add the certificate file and the related rels file
335 382
                    $zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate();
336 382
                    $zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships();
337 382
                }
338 30
            }
339
        }
340
        //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
341
        if ($this->spreadSheet->hasRibbon()) {
342 382
            $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
343
            $tmpRibbonTarget = is_string($tmpRibbonTarget) ? $tmpRibbonTarget : '';
344
            $zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data');
345 382
            if ($this->spreadSheet->hasRibbonBinObjects()) {
346
                $tmpRootPath = dirname($tmpRibbonTarget) . '/';
347
                $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
348 382
                if (is_array($ribbonBinObjects)) {
349
                    foreach ($ribbonBinObjects as $aPath => $aContent) {
350
                        $zipContent[$tmpRootPath . $aPath] = $aContent;
351 382
                    }
352
                }
353 382
                //the rels for files
354
                $zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet);
355 382
            }
356 382
        }
357 381
358 79
        // Add relationships to ZIP file
359 79
        $zipContent['_rels/.rels'] = $this->getWriterPartRels()->writeRelationships($this->spreadSheet);
360 78
        $zipContent['xl/_rels/workbook.xml.rels'] = $this->getWriterPartRels()->writeWorkbookRelationships($this->spreadSheet);
361 78
362 78
        // Add document properties to ZIP file
363
        $zipContent['docProps/app.xml'] = $this->getWriterPartDocProps()->writeDocPropsApp($this->spreadSheet);
364
        $zipContent['docProps/core.xml'] = $this->getWriterPartDocProps()->writeDocPropsCore($this->spreadSheet);
365
        $customPropertiesPart = $this->getWriterPartDocProps()->writeDocPropsCustom($this->spreadSheet);
366
        if ($customPropertiesPart !== null) {
367
            $zipContent['docProps/custom.xml'] = $customPropertiesPart;
368 381
        }
369 381
370
        // Add theme to ZIP file
371 381
        $zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet);
372
373
        // Add string table to ZIP file
374 381
        $zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable);
375
376
        // Add styles to ZIP file
377 381
        $zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet);
378
379 381
        // Add workbook to ZIP file
380
        $zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas, $this->forceFullCalc);
381 381
382 381
        $chartCount = 0;
383
        // Add worksheets
384 4
        for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
385
            $zipContent['xl/worksheets/sheet' . ($i + 1) . '.xml'] = $this->getWriterPartWorksheet()->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts);
386 381
            if ($this->includeCharts) {
387
                $charts = $this->spreadSheet->getSheet($i)->getChartCollection();
388 35
                if (count($charts) > 0) {
389
                    foreach ($charts as $chart) {
390
                        $zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas);
391 381
                        ++$chartCount;
392 381
                    }
393 381
                }
394 79
            }
395
        }
396
397
        $chartRef1 = 0;
398 381
        $tableRef1 = 1;
399
        // Add worksheet relationships (drawings, ...)
400 120
        for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
401
            // Add relationships
402
            /** @var string[] $zipContent */
403 120
            $zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts, $tableRef1, $zipContent);
404 277
405
            // Add unparsedLoadedData
406 4
            $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
407
            /** @var mixed[][][] */
408
            $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
409
            /** @var mixed[][] */
410 381
            $unparsedSheet = $unparsedLoadedData['sheets'][$sheetCodeName] ?? [];
411 5
            foreach (($unparsedSheet['ctrlProps'] ?? []) as $ctrlProp) {
412 5
                /** @var string[] $ctrlProp */
413 5
                $zipContent[$ctrlProp['filePath']] = $ctrlProp['content'];
414
            }
415
            foreach (($unparsedSheet['printerSettings'] ?? []) as $ctrlProp) {
416 5
                /** @var string[] $ctrlProp */
417
                $zipContent[$ctrlProp['filePath']] = $ctrlProp['content'];
418
            }
419
420 381
            $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
421 1
            $drawingCount = count($drawings);
422
            if ($this->includeCharts) {
423
                $chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
424
            }
425
426 381
            // Add drawing and image relationship parts
427 381
            if (($drawingCount > 0) || ($chartCount > 0)) {
428 381
                // Drawing relationships
429 381
                $zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts);
430
431 28
                // Drawings
432
                $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts);
433
            } elseif (isset($unparsedSheet['drawingAlternateContents'])) {
434 28
                // Drawings
435
                $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts);
436
            }
437
438 381
            // Add unparsed drawings
439 26
            if (isset($unparsedSheet['Drawings']) && !isset($zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'])) {
440
                foreach ($unparsedSheet['Drawings'] as $relId => $drawingXml) {
441
                    $drawingFile = array_search($relId, $unparsedSheet['drawingOriginalIds']);
442 26
                    if ($drawingFile !== false) {
443 26
                        //$drawingFile = ltrim($drawingFile, '.');
444 3
                        //$zipContent['xl' . $drawingFile] = $drawingXml;
445 3
                        $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $drawingXml;
446
                    }
447
                }
448
            }
449
            if (isset($unparsedSheet['drawingOriginalIds']) && !isset($zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'])) {
450
                $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = '<xml></xml>';
451 381
            }
452 5
453
            // Add comment relationship parts
454 5
            /** @var mixed[][] */
455 3
            $legacyTemp = $unparsedLoadedData['sheets'] ?? [];
456
            $legacyTemp = $legacyTemp[$this->spreadSheet->getSheet($i)->getCodeName()] ?? [];
457
            $legacy = $legacyTemp['legacyDrawing'] ?? null;
458
            if (count($this->spreadSheet->getSheet($i)->getComments()) > 0 || $legacy !== null) {
459
                // VML Comments relationships
460
                $zipContent['xl/drawings/_rels/vmlDrawing' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeVMLDrawingRelationships($this->spreadSheet->getSheet($i));
461 381
462
                // VML Comments
463 3
                $zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $legacy ?? $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i));
464
            }
465
466 3
            // Comments
467
            if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
468
                $zipContent['xl/comments' . ($i + 1) . '.xml'] = $this->getWriterPartComments()->writeComments($this->spreadSheet->getSheet($i));
469 3
470 3
                // Media
471 3
                foreach ($this->spreadSheet->getSheet($i)->getComments() as $comment) {
472
                    if ($comment->hasBackgroundImage()) {
473
                        $image = $comment->getBackgroundImage();
474
                        $zipContent['xl/media/' . $image->getMediaFilename()] = $this->processDrawing($image);
475
                    }
476
                }
477 381
            }
478 381
479 8
            // Add unparsed relationship parts
480
            if (isset($unparsedSheet['vmlDrawings'])) {
481
                foreach ($unparsedSheet['vmlDrawings'] as $vmlDrawing) {
482
                    /** @var string[] $vmlDrawing */
483
                    if (!isset($zipContent[$vmlDrawing['filePath']])) {
484 381
                        $zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content'];
485 53
                    }
486 42
                }
487 42
            }
488 42
489
            // Add header/footer relationship parts
490
            if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
491 42
                // VML Drawings
492 24
                $zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i));
493 24
494
                // VML Drawing relationships
495 24
                $zipContent['xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i));
496 24
497 24
                // Media
498 24
                foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
499 24
                    if ($image->getPath() !== '') {
500
                        $zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath());
501 20
                    }
502
                }
503
            }
504 42
505 11
            // Add Table parts
506 11
            $tables = $this->spreadSheet->getSheet($i)->getTableCollection();
507 11
            foreach ($tables as $table) {
508 11
                $zipContent['xl/tables/table' . $tableRef1 . '.xml'] = $this->getWriterPartTable()->writeTable($table, $tableRef1++);
509 11
            }
510 11
        }
511 11
512 11
        // Add media
513 11
        for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
514
            if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
515 11
                $imageContents = null;
516
                $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
517
                if ($imagePath === '') {
518
                    continue;
519 381
                }
520 381
                if (str_contains($imagePath, 'zip://')) {
521
                    $imagePath = substr($imagePath, 6);
522 381
                    $imagePathSplitted = explode('#', $imagePath);
523
524 381
                    $imageZip = new ZipArchive();
525
                    $imageZip->open($imagePathSplitted[0]);
526
                    $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
527 381
                    $imageZip->close();
528
                    unset($imageZip);
529
                } else {
530
                    $imageContents = file_get_contents($imagePath);
531 381
                }
532
533
                $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents;
534
            } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
535
                ob_start();
536 381
                $callable = $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction();
537
                call_user_func(
538
                    $callable,
539
                    $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
540
                );
541
                $imageContents = ob_get_contents();
542 438
                ob_end_clean();
543
544 438
                $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents;
545
            }
546
        }
547
548
        Functions::setReturnDateType($saveDateReturnType);
549
        Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
550
551
        $this->openFileHandle($filename);
552
553
        $this->zip = ZipStream0::newZipStream($this->fileHandle);
554 441
555
        /** @var string[] $zipContent */
556 441
        $this->addZipFiles($zipContent);
557
558 441
        // Close file
559
        try {
560
            $this->zip->finish();
561
        } catch (OverflowException) {
562
            throw new WriterException('Could not close resource.');
563
        }
564
565
        $this->maybeCloseFileHandle();
566
    }
567
568
    /**
569
     * Get Spreadsheet object.
570
     */
571
    public function getSpreadsheet(): Spreadsheet
572
    {
573
        return $this->spreadSheet;
574
    }
575
576
    /**
577
     * Set Spreadsheet object.
578
     *
579
     * @param Spreadsheet $spreadsheet PhpSpreadsheet object
580
     *
581
     * @return $this
582
     */
583
    public function setSpreadsheet(Spreadsheet $spreadsheet): static
584
    {
585
        $this->spreadSheet = $spreadsheet;
586 417
587
        return $this;
588 417
    }
589
590
    /**
591
     * Get string table.
592
     *
593
     * @return string[]
594
     */
595
    public function getStringTable(): array
596 383
    {
597
        return $this->stringTable;
598 383
    }
599
600
    /**
601
     * Get Style HashTable.
602
     *
603
     * @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style>
604
     */
605
    public function getStyleHashTable(): HashTable
606 383
    {
607
        return $this->styleHashTable;
608 383
    }
609
610
    /**
611
     * Get Conditional HashTable.
612
     *
613
     * @return HashTable<Conditional>
614
     */
615
    public function getStylesConditionalHashTable(): HashTable
616 383
    {
617
        return $this->stylesConditionalHashTable;
618 383
    }
619
620
    /**
621
     * Get Fill HashTable.
622
     *
623
     * @return HashTable<Fill>
624
     */
625
    public function getFillHashTable(): HashTable
626 383
    {
627
        return $this->fillHashTable;
628 383
    }
629
630
    /**
631
     * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
632
     *
633
     * @return HashTable<Font>
634
     */
635
    public function getFontHashTable(): HashTable
636 382
    {
637
        return $this->fontHashTable;
638 382
    }
639
640
    /**
641
     * Get Borders HashTable.
642
     *
643
     * @return HashTable<Borders>
644 384
     */
645
    public function getBordersHashTable(): HashTable
646 384
    {
647
        return $this->bordersHashTable;
648
    }
649
650
    /**
651
     * Get NumberFormat HashTable.
652
     *
653
     * @return HashTable<NumberFormat>
654
     */
655
    public function getNumFmtHashTable(): HashTable
656
    {
657
        return $this->numFmtHashTable;
658
    }
659
660
    /**
661
     * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
662
     *
663
     * @return HashTable<BaseDrawing>
664
     */
665
    public function getDrawingHashTable(): HashTable
666 381
    {
667
        return $this->drawingHashTable;
668 381
    }
669 381
670 381
    /**
671
     * Get Office2003 compatibility.
672
     */
673
    public function getOffice2003Compatibility(): bool
674
    {
675 381
        return $this->office2003compatibility;
676
    }
677 381
678 381
    /**
679
     * Set Office2003 compatibility.
680
     *
681
     * @param bool $office2003compatibility Office2003 compatibility?
682 3
     *
683
     * @return $this
684 3
     */
685 3
    public function setOffice2003Compatibility(bool $office2003compatibility): static
686 3
    {
687
        $this->office2003compatibility = $office2003compatibility;
688
689 3
        return $this;
690
    }
691 3
692 3
    /** @var string[] */
693 3
    private array $pathNames = [];
694 2
695 2
    private function addZipFile(string $path, string $content): void
696 2
    {
697 2
        if (!in_array($path, $this->pathNames)) {
698 2
            $this->pathNames[] = $path;
699 2
            $this->zip->addFile($path, $content);
700
        }
701
    }
702 2
703
    /** @param string[] $zipContent */
704 3
    private function addZipFiles(array $zipContent): void
705 2
    {
706
        foreach ($zipContent as $path => $content) {
707 2
            $this->addZipFile($path, $content);
708
        }
709 2
    }
710 1
711
    private function processDrawing(WorksheetDrawing $drawing): string|null|false
712 1
    {
713
        $data = null;
714 2
        $filename = $drawing->getPath();
715 2
        if ($filename === '') {
716 2
            return null;
717 2
        }
718 2
        $imageData = getimagesize($filename);
719 2
720 2
        if (!empty($imageData)) {
721
            switch ($imageData[2]) {
722
                case 1: // GIF, not supported by BIFF8, we convert to PNG
723 2
                    $image = imagecreatefromgif($filename);
724
                    if ($image !== false) {
725
                        ob_start();
726
                        imagepng($image);
727 3
                        $data = ob_get_contents();
728
                        ob_end_clean();
729
                    }
730 425
731
                    break;
732 425
733
                case 2: // JPEG
734
                    $data = file_get_contents($filename);
735
736
                    break;
737
738
                case 3: // PNG
739
                    $data = file_get_contents($filename);
740 1
741
                    break;
742 1
743
                case 6: // Windows DIB (BMP), we convert to PNG
744 1
                    $image = imagecreatefrombmp($filename);
745
                    if ($image !== false) {
746
                        ob_start();
747 2
                        imagepng($image);
748
                        $data = ob_get_contents();
749 2
                        ob_end_clean();
750 2
                    }
751
752 2
                    break;
753
            }
754
        }
755 426
756
        return $data;
757 426
    }
758
759
    public function getExplicitStyle0(): bool
760 441
    {
761
        return $this->explicitStyle0;
762 441
    }
763
764
    /**
765
     * This may be useful if non-default Alignment is part of default style
766
     * and you think you might want to open the spreadsheet
767
     * with LibreOffice or Gnumeric.
768
     */
769
    public function setExplicitStyle0(bool $explicitStyle0): self
770
    {
771
        $this->explicitStyle0 = $explicitStyle0;
772
773
        return $this;
774
    }
775 4
776
    public function setUseCSEArrays(?bool $useCSEArrays): void
777 4
    {
778
        if ($useCSEArrays !== null) {
779 4
            $this->useCSEArrays = $useCSEArrays;
780
        }
781
        $this->determineUseDynamicArrays();
782
    }
783
784
    public function useDynamicArrays(): bool
785
    {
786
        return $this->useDynamicArray;
787
    }
788
789
    private function determineUseDynamicArrays(): void
790
    {
791
        $this->useDynamicArray = $this->preCalculateFormulas && Calculation::getInstance($this->spreadSheet)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY && !$this->useCSEArrays;
792
    }
793
794
    /**
795
     * If this is set when a spreadsheet is opened,
796
     * values may not be automatically re-calculated,
797
     * and a button will be available to force re-calculation.
798
     * This may apply to all spreadsheets open at that time.
799
     * If null, this will be set to the opposite of $preCalculateFormulas.
800
     * It is likely that false is the desired setting, although
801
     * cases have been reported where true is required (issue #456).
802
     * Nevertheless, default is set to false in PhpSpreadsheet 4.0.0.
803
     */
804
    public function setForceFullCalc(?bool $forceFullCalc): self
805
    {
806
        $this->forceFullCalc = $forceFullCalc;
807
808
        return $this;
809
    }
810
}
811