Passed
Pull Request — master (#4327)
by Owen
15:24 queued 04:35
created

Spreadsheet   F

Complexity

Total Complexity 234

Size/Duplication

Total Lines 1663
Duplicated Lines 0 %

Test Coverage

Coverage 98.1%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 234
eloc 459
c 3
b 0
f 0
dl 0
loc 1663
ccs 517
cts 527
cp 0.981
rs 2

107 Methods

Rating   Name   Duplication   Size   Complexity  
A getMacrosCertificate() 0 3 1
A hasMacrosCertificate() 0 3 1
A getTheme() 0 3 1
A disconnectWorksheets() 0 7 2
A getSheetByCodeName() 0 10 3
A getProperties() 0 3 1
A __construct() 0 27 1
A hasMacros() 0 3 1
A getSecurity() 0 3 1
A getCalculationEngine() 0 3 1
A hasRibbon() 0 3 1
A setUnparsedLoadedData() 0 3 1
B getRibbonBinObjects() 0 29 10
A setProperties() 0 3 1
A getActiveSheet() 0 3 1
A discardMacros() 0 5 1
A getUnparsedLoadedData() 0 3 1
A setRibbonBinObjects() 0 6 3
A hasRibbonBinObjects() 0 3 1
A setSecurity() 0 3 1
A getMacrosCode() 0 3 1
A __destruct() 0 7 1
A setMacrosCertificate() 0 3 1
A setRibbonXMLData() 0 6 3
A sheetCodeNameExists() 0 3 1
A setHasMacros() 0 3 1
A getRibbonXMLData() 0 19 5
A sheetNameExists() 0 3 1
A setMacrosCode() 0 4 1
A createSheet() 0 6 1
A addNamedRange() 0 3 1
A getDefinedNames() 0 3 1
A getGlobalDefinedNameByType() 0 7 3
A addNamedFormula() 0 3 1
A getWorksheetIterator() 0 3 1
A removeDefinedName() 0 17 5
A getSheetCount() 0 3 1
A getAllSheets() 0 3 1
A getLocalDefinedNameByType() 0 10 4
A removeNamedRange() 0 7 2
A addDefinedName() 0 9 2
A duplicateWorksheetByTitle() 0 7 1
A getNamedRange() 0 13 4
A getSheetByName() 0 10 3
A getActiveSheetIndex() 0 3 1
A removeSheetByIndex() 0 16 5
A getNamedFormulae() 0 5 1
A getCellXfCollection() 0 3 1
A removeNamedFormula() 0 7 2
A getDefinedName() 0 18 5
A setIndexByName() 0 16 1
A getSheetByNameOrThrow() 0 8 2
A getSheet() 0 11 2
A __clone() 0 4 1
A getIndex() 0 13 4
A getNamedFormula() 0 13 4
A getSheetNames() 0 9 2
B addExternalSheet() 0 37 7
A copy() 0 13 1
A getNamedRanges() 0 5 1
A getCellXfByIndex() 0 3 1
A setActiveSheetIndex() 0 12 2
B addSheet() 0 48 10
A setActiveSheetIndexByName() 0 9 2
A getValueBinder() 0 3 1
A setShowVerticalScroll() 0 3 1
A getShowHorizontalScroll() 0 3 1
A getLegacyDrawing() 0 3 1
A setShowHorizontalScroll() 0 3 1
A removeCellStyleXfByIndex() 0 6 2
A setAutoFilterDateGrouping() 0 3 1
A getVisibility() 0 3 1
A getCellStyleXfByIndex() 0 3 1
A addCellStyleXf() 0 4 1
A setFirstSheetIndex() 0 6 2
A getShowSheetTabs() 0 3 1
A setValueBinder() 0 5 1
A getCellStyleXfCollection() 0 3 1
A getTabRatio() 0 3 1
A jsonSerialize() 0 3 1
A __serialize() 0 3 1
A getCellStyleXfByHashCode() 0 9 3
A setShowSheetTabs() 0 3 1
F garbageCollect() 0 74 17
A setExcelCalendar() 0 9 3
A getExcelCalendar() 0 3 1
A setMinimized() 0 3 1
A cellXfExists() 0 3 1
A getCellXfByIndexOrNull() 0 3 2
A getCellXfByHashCode() 0 9 3
A addCellXf() 0 4 1
A getID() 0 3 1
A getDefaultStyle() 0 7 2
A setTabRatio() 0 6 3
A getAutoFilterDateGrouping() 0 3 1
A getShowVerticalScroll() 0 3 1
A deleteLegacyDrawing() 0 3 1
A getFirstSheetIndex() 0 3 1
B resetThemeFonts() 0 18 7
A reevaluateAutoFilters() 0 9 4
A setVisibility() 0 10 3
A getCellXfSupervisor() 0 3 1
A getMinimized() 0 3 1
A removeCellXfByIndex() 0 20 6
A getTableByName() 0 11 3
A mergeChartCellsForPdf() 0 11 6
A mergeDrawingCellsForPdf() 0 11 6

How to fix   Complexity   

Complex Class

Complex classes like Spreadsheet often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Spreadsheet, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet;
4
5
use JsonSerializable;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
8
use PhpOffice\PhpSpreadsheet\Document\Properties;
9
use PhpOffice\PhpSpreadsheet\Document\Security;
10
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader;
11
use PhpOffice\PhpSpreadsheet\Shared\Date;
12
use PhpOffice\PhpSpreadsheet\Shared\File;
13
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
14
use PhpOffice\PhpSpreadsheet\Style\Style;
15
use PhpOffice\PhpSpreadsheet\Worksheet\Iterator;
16
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
17
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
18
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
19
20
class Spreadsheet implements JsonSerializable
21
{
22
    // Allowable values for workbook window visilbity
23
    const VISIBILITY_VISIBLE = 'visible';
24
    const VISIBILITY_HIDDEN = 'hidden';
25
    const VISIBILITY_VERY_HIDDEN = 'veryHidden';
26
27
    private const DEFINED_NAME_IS_RANGE = false;
28
    private const DEFINED_NAME_IS_FORMULA = true;
29
30
    private const WORKBOOK_VIEW_VISIBILITY_VALUES = [
31
        self::VISIBILITY_VISIBLE,
32
        self::VISIBILITY_HIDDEN,
33
        self::VISIBILITY_VERY_HIDDEN,
34
    ];
35
36
    protected int $excelCalendar = Date::CALENDAR_WINDOWS_1900;
37
38
    /**
39
     * Unique ID.
40
     */
41
    private string $uniqueID;
42
43
    /**
44
     * Document properties.
45
     */
46
    private Properties $properties;
47
48
    /**
49
     * Document security.
50
     */
51
    private Security $security;
52
53
    /**
54
     * Collection of Worksheet objects.
55
     *
56
     * @var Worksheet[]
57
     */
58
    private array $workSheetCollection;
59
60
    /**
61
     * Calculation Engine.
62
     */
63
    private ?Calculation $calculationEngine;
64
65
    /**
66
     * Active sheet index.
67
     */
68
    private int $activeSheetIndex;
69
70
    /**
71
     * Named ranges.
72
     *
73
     * @var DefinedName[]
74
     */
75
    private array $definedNames;
76
77
    /**
78
     * CellXf supervisor.
79
     */
80
    private Style $cellXfSupervisor;
81
82
    /**
83
     * CellXf collection.
84
     *
85
     * @var Style[]
86
     */
87
    private array $cellXfCollection = [];
88
89
    /**
90
     * CellStyleXf collection.
91
     *
92
     * @var Style[]
93
     */
94
    private array $cellStyleXfCollection = [];
95
96
    /**
97
     * hasMacros : this workbook have macros ?
98
     */
99
    private bool $hasMacros = false;
100
101
    /**
102
     * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code,  etc.), null if no macro.
103
     */
104
    private ?string $macrosCode = null;
105
106
    /**
107
     * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed.
108
     */
109
    private ?string $macrosCertificate = null;
110
111
    /**
112
     * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI.
113
     *
114
     * @var null|array{target: string, data: string}
115
     */
116
    private ?array $ribbonXMLData = null;
117
118
    /**
119
     * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements
120
     * ignored if $ribbonXMLData is null.
121
     */
122
    private ?array $ribbonBinObjects = null;
123
124
    /**
125
     * List of unparsed loaded data for export to same format with better compatibility.
126
     * It has to be minimized when the library start to support currently unparsed data.
127
     */
128
    private array $unparsedLoadedData = [];
129
130
    /**
131
     * Controls visibility of the horizonal scroll bar in the application.
132
     */
133
    private bool $showHorizontalScroll = true;
134
135
    /**
136
     * Controls visibility of the horizonal scroll bar in the application.
137
     */
138
    private bool $showVerticalScroll = true;
139
140
    /**
141
     * Controls visibility of the sheet tabs in the application.
142
     */
143
    private bool $showSheetTabs = true;
144
145
    /**
146
     * Specifies a boolean value that indicates whether the workbook window
147
     * is minimized.
148
     */
149
    private bool $minimized = false;
150
151
    /**
152
     * Specifies a boolean value that indicates whether to group dates
153
     * when presenting the user with filtering optiomd in the user
154
     * interface.
155
     */
156
    private bool $autoFilterDateGrouping = true;
157
158
    /**
159
     * Specifies the index to the first sheet in the book view.
160
     */
161
    private int $firstSheetIndex = 0;
162
163
    /**
164
     * Specifies the visible status of the workbook.
165
     */
166
    private string $visibility = self::VISIBILITY_VISIBLE;
167
168
    /**
169
     * Specifies the ratio between the workbook tabs bar and the horizontal
170
     * scroll bar.  TabRatio is assumed to be out of 1000 of the horizontal
171
     * window width.
172
     */
173
    private int $tabRatio = 600;
174
175
    private Theme $theme;
176
177
    private ?IValueBinder $valueBinder = null;
178
179 745
    public function getTheme(): Theme
180
    {
181 745
        return $this->theme;
182
    }
183
184
    /**
185
     * The workbook has macros ?
186
     */
187 404
    public function hasMacros(): bool
188
    {
189 404
        return $this->hasMacros;
190
    }
191
192
    /**
193
     * Define if a workbook has macros.
194
     *
195
     * @param bool $hasMacros true|false
196
     */
197 3
    public function setHasMacros(bool $hasMacros): void
198
    {
199 3
        $this->hasMacros = (bool) $hasMacros;
200
    }
201
202
    /**
203
     * Set the macros code.
204
     *
205
     * @param string $macroCode string|null
206
     */
207 3
    public function setMacrosCode(string $macroCode): void
208
    {
209 3
        $this->macrosCode = $macroCode;
210 3
        $this->setHasMacros($macroCode !== null);
211
    }
212
213
    /**
214
     * Return the macros code.
215
     */
216 3
    public function getMacrosCode(): ?string
217
    {
218 3
        return $this->macrosCode;
219
    }
220
221
    /**
222
     * Set the macros certificate.
223
     */
224 3
    public function setMacrosCertificate(?string $certificate): void
225
    {
226 3
        $this->macrosCertificate = $certificate;
227
    }
228
229
    /**
230
     * Is the project signed ?
231
     *
232
     * @return bool true|false
233
     */
234 2
    public function hasMacrosCertificate(): bool
235
    {
236 2
        return $this->macrosCertificate !== null;
237
    }
238
239
    /**
240
     * Return the macros certificate.
241
     */
242 2
    public function getMacrosCertificate(): ?string
243
    {
244 2
        return $this->macrosCertificate;
245
    }
246
247
    /**
248
     * Remove all macros, certificate from spreadsheet.
249
     */
250 1
    public function discardMacros(): void
251
    {
252 1
        $this->hasMacros = false;
253 1
        $this->macrosCode = null;
254 1
        $this->macrosCertificate = null;
255
    }
256
257
    /**
258
     * set ribbon XML data.
259
     */
260 2
    public function setRibbonXMLData(mixed $target, mixed $xmlData): void
261
    {
262 2
        if (is_string($target) && is_string($xmlData)) {
263 2
            $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData];
264
        } else {
265
            $this->ribbonXMLData = null;
266
        }
267
    }
268
269
    /**
270
     * retrieve ribbon XML Data.
271
     */
272 365
    public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here...
273
    {
274 365
        $returnData = null;
275 365
        $what = strtolower($what);
276
        switch ($what) {
277 365
            case 'all':
278 2
                $returnData = $this->ribbonXMLData;
279
280 2
                break;
281 365
            case 'target':
282 2
            case 'data':
283 365
                if (is_array($this->ribbonXMLData)) {
284 2
                    $returnData = $this->ribbonXMLData[$what];
285
                }
286
287 365
                break;
288
        }
289
290 365
        return $returnData;
291
    }
292
293
    /**
294
     * store binaries ribbon objects (pictures).
295
     */
296 2
    public function setRibbonBinObjects(mixed $binObjectsNames, mixed $binObjectsData): void
297
    {
298 2
        if ($binObjectsNames !== null && $binObjectsData !== null) {
299
            $this->ribbonBinObjects = ['names' => $binObjectsNames, 'data' => $binObjectsData];
300
        } else {
301 2
            $this->ribbonBinObjects = null;
302
        }
303
    }
304
305
    /**
306
     * List of unparsed loaded data for export to same format with better compatibility.
307
     * It has to be minimized when the library start to support currently unparsed data.
308
     *
309
     * @internal
310
     */
311 405
    public function getUnparsedLoadedData(): array
312
    {
313 405
        return $this->unparsedLoadedData;
314
    }
315
316
    /**
317
     * List of unparsed loaded data for export to same format with better compatibility.
318
     * It has to be minimized when the library start to support currently unparsed data.
319
     *
320
     * @internal
321
     */
322 638
    public function setUnparsedLoadedData(array $unparsedLoadedData): void
323
    {
324 638
        $this->unparsedLoadedData = $unparsedLoadedData;
325
    }
326
327
    /**
328
     * retrieve Binaries Ribbon Objects.
329
     */
330 2
    public function getRibbonBinObjects(string $what = 'all'): ?array
331
    {
332 2
        $ReturnData = null;
333 2
        $what = strtolower($what);
334
        switch ($what) {
335 2
            case 'all':
336 2
                return $this->ribbonBinObjects;
337 1
            case 'names':
338 1
            case 'data':
339 1
                if (is_array($this->ribbonBinObjects) && isset($this->ribbonBinObjects[$what])) {
340
                    $ReturnData = $this->ribbonBinObjects[$what];
341
                }
342
343 1
                break;
344 1
            case 'types':
345
                if (
346 1
                    is_array($this->ribbonBinObjects)
347 1
                    && isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data'])
348
                ) {
349
                    $tmpTypes = array_keys($this->ribbonBinObjects['data']);
350
                    $ReturnData = array_unique(array_map(fn (string $path): string => pathinfo($path, PATHINFO_EXTENSION), $tmpTypes));
351
                } else {
352 1
                    $ReturnData = []; // the caller want an array... not null if empty
353
                }
354
355 1
                break;
356
        }
357
358 1
        return $ReturnData;
359
    }
360
361
    /**
362
     * This workbook have a custom UI ?
363
     */
364 365
    public function hasRibbon(): bool
365
    {
366 365
        return $this->ribbonXMLData !== null;
367
    }
368
369
    /**
370
     * This workbook have additionnal object for the ribbon ?
371
     */
372 365
    public function hasRibbonBinObjects(): bool
373
    {
374 365
        return $this->ribbonBinObjects !== null;
375
    }
376
377
    /**
378
     * Check if a sheet with a specified code name already exists.
379
     *
380
     * @param string $codeName Name of the worksheet to check
381
     */
382 10393
    public function sheetCodeNameExists(string $codeName): bool
383
    {
384 10393
        return $this->getSheetByCodeName($codeName) !== null;
385
    }
386
387
    /**
388
     * Get sheet by code name. Warning : sheet don't have always a code name !
389
     *
390
     * @param string $codeName Sheet name
391
     */
392 10393
    public function getSheetByCodeName(string $codeName): ?Worksheet
393
    {
394 10393
        $worksheetCount = count($this->workSheetCollection);
395 10393
        for ($i = 0; $i < $worksheetCount; ++$i) {
396 707
            if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
397 673
                return $this->workSheetCollection[$i];
398
            }
399
        }
400
401 10393
        return null;
402
    }
403
404
    /**
405
     * Create a new PhpSpreadsheet with one Worksheet.
406
     */
407 10393
    public function __construct()
408
    {
409 10393
        $this->uniqueID = uniqid('', true);
410 10393
        $this->calculationEngine = new Calculation($this);
411 10393
        $this->theme = new Theme();
412
413
        // Initialise worksheet collection and add one worksheet
414 10393
        $this->workSheetCollection = [];
415 10393
        $this->workSheetCollection[] = new Worksheet($this);
416 10393
        $this->activeSheetIndex = 0;
417
418
        // Create document properties
419 10393
        $this->properties = new Properties();
420
421
        // Create document security
422 10393
        $this->security = new Security();
423
424
        // Set defined names
425 10393
        $this->definedNames = [];
426
427
        // Create the cellXf supervisor
428 10393
        $this->cellXfSupervisor = new Style(true);
429 10393
        $this->cellXfSupervisor->bindParent($this);
430
431
        // Create the default style
432 10393
        $this->addCellXf(new Style());
433 10393
        $this->addCellStyleXf(new Style());
434
    }
435
436
    /**
437
     * Code to execute when this worksheet is unset().
438
     */
439 111
    public function __destruct()
440
    {
441 111
        $this->disconnectWorksheets();
442 111
        $this->calculationEngine = null;
443 111
        $this->cellXfCollection = [];
444 111
        $this->cellStyleXfCollection = [];
445 111
        $this->definedNames = [];
446
    }
447
448
    /**
449
     * Disconnect all worksheets from this PhpSpreadsheet workbook object,
450
     * typically so that the PhpSpreadsheet object can be unset.
451
     */
452 9039
    public function disconnectWorksheets(): void
453
    {
454 9039
        foreach ($this->workSheetCollection as $worksheet) {
455 9036
            $worksheet->disconnectCells();
456 9036
            unset($worksheet);
457
        }
458 9039
        $this->workSheetCollection = [];
459
    }
460
461
    /**
462
     * Return the calculation engine for this worksheet.
463
     */
464 9499
    public function getCalculationEngine(): ?Calculation
465
    {
466 9499
        return $this->calculationEngine;
467
    }
468
469
    /**
470
     * Get properties.
471
     */
472 1557
    public function getProperties(): Properties
473
    {
474 1557
        return $this->properties;
475
    }
476
477
    /**
478
     * Set properties.
479
     */
480 1
    public function setProperties(Properties $documentProperties): void
481
    {
482 1
        $this->properties = $documentProperties;
483
    }
484
485
    /**
486
     * Get security.
487
     */
488 378
    public function getSecurity(): Security
489
    {
490 378
        return $this->security;
491
    }
492
493
    /**
494
     * Set security.
495
     */
496 1
    public function setSecurity(Security $documentSecurity): void
497
    {
498 1
        $this->security = $documentSecurity;
499
    }
500
501
    /**
502
     * Get active sheet.
503
     */
504 10326
    public function getActiveSheet(): Worksheet
505
    {
506 10326
        return $this->getSheet($this->activeSheetIndex);
507
    }
508
509
    /**
510
     * Create sheet and add it to this workbook.
511
     *
512
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
513
     */
514 1181
    public function createSheet(?int $sheetIndex = null): Worksheet
515
    {
516 1181
        $newSheet = new Worksheet($this);
517 1181
        $this->addSheet($newSheet, $sheetIndex, true);
518
519 1181
        return $newSheet;
520
    }
521
522
    /**
523
     * Check if a sheet with a specified name already exists.
524
     *
525
     * @param string $worksheetName Name of the worksheet to check
526
     */
527 1753
    public function sheetNameExists(string $worksheetName): bool
528
    {
529 1753
        return $this->getSheetByName($worksheetName) !== null;
530
    }
531
532 1
    public function duplicateWorksheetByTitle(string $title): Worksheet
533
    {
534 1
        $original = $this->getSheetByNameOrThrow($title);
535 1
        $index = $this->getIndex($original) + 1;
536 1
        $clone = clone $original;
537
538 1
        return $this->addSheet($clone, $index, true);
539
    }
540
541
    /**
542
     * Add sheet.
543
     *
544
     * @param Worksheet $worksheet The worksheet to add
545
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
546
     */
547 1272
    public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet
548
    {
549 1272
        if ($retitleIfNeeded) {
550 1181
            $title = $worksheet->getTitle();
551 1181
            if ($this->sheetNameExists($title)) {
552 159
                $i = 1;
553 159
                $newTitle = "$title $i";
554 159
                while ($this->sheetNameExists($newTitle)) {
555 27
                    ++$i;
556 27
                    $newTitle = "$title $i";
557
                }
558 159
                $worksheet->setTitle($newTitle);
559
            }
560
        }
561 1272
        if ($this->sheetNameExists($worksheet->getTitle())) {
562 2
            throw new Exception(
563 2
                "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
564 2
            );
565
        }
566
567 1272
        if ($sheetIndex === null) {
568 1239
            if ($this->activeSheetIndex < 0) {
569 861
                $this->activeSheetIndex = 0;
570
            }
571 1239
            $this->workSheetCollection[] = $worksheet;
572
        } else {
573
            // Insert the sheet at the requested index
574 38
            array_splice(
575 38
                $this->workSheetCollection,
576 38
                $sheetIndex,
577 38
                0,
578 38
                [$worksheet]
579 38
            );
580
581
            // Adjust active sheet index if necessary
582 38
            if ($this->activeSheetIndex >= $sheetIndex) {
583 30
                ++$this->activeSheetIndex;
584
            }
585 38
            if ($this->activeSheetIndex < 0) {
586 3
                $this->activeSheetIndex = 0;
587
            }
588
        }
589
590 1272
        if ($worksheet->getParent() === null) {
591 51
            $worksheet->rebindParent($this);
592
        }
593
594 1272
        return $worksheet;
595
    }
596
597
    /**
598
     * Remove sheet by index.
599
     *
600
     * @param int $sheetIndex Index position of the worksheet to remove
601
     */
602 901
    public function removeSheetByIndex(int $sheetIndex): void
603
    {
604 901
        $numSheets = count($this->workSheetCollection);
605 901
        if ($sheetIndex > $numSheets - 1) {
606 1
            throw new Exception(
607 1
                "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
608 1
            );
609
        }
610 900
        array_splice($this->workSheetCollection, $sheetIndex, 1);
611
612
        // Adjust active sheet index if necessary
613
        if (
614 900
            ($this->activeSheetIndex >= $sheetIndex)
615 900
            && ($this->activeSheetIndex > 0 || $numSheets <= 1)
616
        ) {
617 898
            --$this->activeSheetIndex;
618
        }
619
    }
620
621
    /**
622
     * Get sheet by index.
623
     *
624
     * @param int $sheetIndex Sheet index
625
     */
626 10331
    public function getSheet(int $sheetIndex): Worksheet
627
    {
628 10331
        if (!isset($this->workSheetCollection[$sheetIndex])) {
629 1
            $numSheets = $this->getSheetCount();
630
631 1
            throw new Exception(
632 1
                "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
633 1
            );
634
        }
635
636 10331
        return $this->workSheetCollection[$sheetIndex];
637
    }
638
639
    /**
640
     * Get all sheets.
641
     *
642
     * @return Worksheet[]
643
     */
644 158
    public function getAllSheets(): array
645
    {
646 158
        return $this->workSheetCollection;
647
    }
648
649
    /**
650
     * Get sheet by name.
651
     *
652
     * @param string $worksheetName Sheet name
653
     */
654 9346
    public function getSheetByName(string $worksheetName): ?Worksheet
655
    {
656 9346
        $worksheetCount = count($this->workSheetCollection);
657 9346
        for ($i = 0; $i < $worksheetCount; ++$i) {
658 9035
            if (strcasecmp($this->workSheetCollection[$i]->getTitle(), trim($worksheetName, "'")) === 0) {
659 8456
                return $this->workSheetCollection[$i];
660
            }
661
        }
662
663 1765
        return null;
664
    }
665
666
    /**
667
     * Get sheet by name, throwing exception if not found.
668
     */
669 232
    public function getSheetByNameOrThrow(string $worksheetName): Worksheet
670
    {
671 232
        $worksheet = $this->getSheetByName($worksheetName);
672 232
        if ($worksheet === null) {
673 1
            throw new Exception("Sheet $worksheetName does not exist.");
674
        }
675
676 231
        return $worksheet;
677
    }
678
679
    /**
680
     * Get index for sheet.
681
     *
682
     * @return int index
683
     */
684 10393
    public function getIndex(Worksheet $worksheet, bool $noThrow = false): int
685
    {
686 10393
        $wsHash = $worksheet->getHashInt();
687 10393
        foreach ($this->workSheetCollection as $key => $value) {
688 10180
            if ($value->getHashInt() === $wsHash) {
689 10168
                return $key;
690
            }
691
        }
692 10393
        if ($noThrow) {
693 10393
            return -1;
694
        }
695
696 3
        throw new Exception('Sheet does not exist.');
697
    }
698
699
    /**
700
     * Set index for sheet by sheet name.
701
     *
702
     * @param string $worksheetName Sheet name to modify index for
703
     * @param int $newIndexPosition New index for the sheet
704
     *
705
     * @return int New sheet index
706
     */
707 1
    public function setIndexByName(string $worksheetName, int $newIndexPosition): int
708
    {
709 1
        $oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName));
710 1
        $worksheet = array_splice(
711 1
            $this->workSheetCollection,
712 1
            $oldIndex,
713 1
            1
714 1
        );
715 1
        array_splice(
716 1
            $this->workSheetCollection,
717 1
            $newIndexPosition,
718 1
            0,
719 1
            $worksheet
720 1
        );
721
722 1
        return $newIndexPosition;
723
    }
724
725
    /**
726
     * Get sheet count.
727
     */
728 1535
    public function getSheetCount(): int
729
    {
730 1535
        return count($this->workSheetCollection);
731
    }
732
733
    /**
734
     * Get active sheet index.
735
     *
736
     * @return int Active sheet index
737
     */
738 10053
    public function getActiveSheetIndex(): int
739
    {
740 10053
        return $this->activeSheetIndex;
741
    }
742
743
    /**
744
     * Set active sheet index.
745
     *
746
     * @param int $worksheetIndex Active sheet index
747
     */
748 10130
    public function setActiveSheetIndex(int $worksheetIndex): Worksheet
749
    {
750 10130
        $numSheets = count($this->workSheetCollection);
751
752 10130
        if ($worksheetIndex > $numSheets - 1) {
753 6
            throw new Exception(
754 6
                "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
755 6
            );
756
        }
757 10124
        $this->activeSheetIndex = $worksheetIndex;
758
759 10124
        return $this->getActiveSheet();
760
    }
761
762
    /**
763
     * Set active sheet index by name.
764
     *
765
     * @param string $worksheetName Sheet title
766
     */
767 95
    public function setActiveSheetIndexByName(string $worksheetName): Worksheet
768
    {
769 95
        if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
770 93
            $this->setActiveSheetIndex($this->getIndex($worksheet));
771
772 93
            return $worksheet;
773
        }
774
775 2
        throw new Exception('Workbook does not contain sheet:' . $worksheetName);
776
    }
777
778
    /**
779
     * Get sheet names.
780
     *
781
     * @return string[]
782
     */
783 10
    public function getSheetNames(): array
784
    {
785 10
        $returnValue = [];
786 10
        $worksheetCount = $this->getSheetCount();
787 10
        for ($i = 0; $i < $worksheetCount; ++$i) {
788 10
            $returnValue[] = $this->getSheet($i)->getTitle();
789
        }
790
791 10
        return $returnValue;
792
    }
793
794
    /**
795
     * Add external sheet.
796
     *
797
     * @param Worksheet $worksheet External sheet to add
798
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
799
     */
800 5
    public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet
801
    {
802 5
        if ($this->sheetNameExists($worksheet->getTitle())) {
803 1
            throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
804
        }
805
806
        // count how many cellXfs there are in this workbook currently, we will need this below
807 4
        $countCellXfs = count($this->cellXfCollection);
808
809
        // copy all the shared cellXfs from the external workbook and append them to the current
810 4
        foreach ($worksheet->getParentOrThrow()->getCellXfCollection() as $cellXf) {
811 4
            $this->addCellXf(clone $cellXf);
812
        }
813
814
        // move sheet to this workbook
815 4
        $worksheet->rebindParent($this);
816
817
        // update the cellXfs
818 4
        foreach ($worksheet->getCoordinates(false) as $coordinate) {
819 4
            $cell = $worksheet->getCell($coordinate);
820 4
            $cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
821
        }
822
823
        // update the column dimensions Xfs
824 4
        foreach ($worksheet->getColumnDimensions() as $columnDimension) {
825 1
            $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs);
826
        }
827
828
        // update the row dimensions Xfs
829 4
        foreach ($worksheet->getRowDimensions() as $rowDimension) {
830 1
            $xfIndex = $rowDimension->getXfIndex();
831 1
            if ($xfIndex !== null) {
832 1
                $rowDimension->setXfIndex($xfIndex + $countCellXfs);
833
            }
834
        }
835
836 4
        return $this->addSheet($worksheet, $sheetIndex);
837
    }
838
839
    /**
840
     * Get an array of all Named Ranges.
841
     *
842
     * @return DefinedName[]
843
     */
844 9
    public function getNamedRanges(): array
845
    {
846 9
        return array_filter(
847 9
            $this->definedNames,
848 9
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE
849 9
        );
850
    }
851
852
    /**
853
     * Get an array of all Named Formulae.
854
     *
855
     * @return DefinedName[]
856
     */
857 15
    public function getNamedFormulae(): array
858
    {
859 15
        return array_filter(
860 15
            $this->definedNames,
861 15
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA
862 15
        );
863
    }
864
865
    /**
866
     * Get an array of all Defined Names (both named ranges and named formulae).
867
     *
868
     * @return DefinedName[]
869
     */
870 551
    public function getDefinedNames(): array
871
    {
872 551
        return $this->definedNames;
873
    }
874
875
    /**
876
     * Add a named range.
877
     * If a named range with this name already exists, then this will replace the existing value.
878
     */
879 305
    public function addNamedRange(NamedRange $namedRange): void
880
    {
881 305
        $this->addDefinedName($namedRange);
882
    }
883
884
    /**
885
     * Add a named formula.
886
     * If a named formula with this name already exists, then this will replace the existing value.
887
     */
888 12
    public function addNamedFormula(NamedFormula $namedFormula): void
889
    {
890 12
        $this->addDefinedName($namedFormula);
891
    }
892
893
    /**
894
     * Add a defined name (either a named range or a named formula).
895
     * If a defined named with this name already exists, then this will replace the existing value.
896
     */
897 423
    public function addDefinedName(DefinedName $definedName): void
898
    {
899 423
        $upperCaseName = StringHelper::strToUpper($definedName->getName());
900 423
        if ($definedName->getScope() == null) {
901
            // global scope
902 410
            $this->definedNames[$upperCaseName] = $definedName;
903
        } else {
904
            // local scope
905 121
            $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName;
906
        }
907
    }
908
909
    /**
910
     * Get named range.
911
     *
912
     * @param null|Worksheet $worksheet Scope. Use null for global scope
913
     */
914 26
    public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
915
    {
916 26
        $returnValue = null;
917
918 26
        if ($namedRange !== '') {
919 26
            $namedRange = StringHelper::strToUpper($namedRange);
920
            // first look for global named range
921 26
            $returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE);
922
            // then look for local named range (has priority over global named range if both names exist)
923 26
            $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
924
        }
925
926 26
        return $returnValue instanceof NamedRange ? $returnValue : null;
927
    }
928
929
    /**
930
     * Get named formula.
931
     *
932
     * @param null|Worksheet $worksheet Scope. Use null for global scope
933
     */
934 11
    public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
935
    {
936 11
        $returnValue = null;
937
938 11
        if ($namedFormula !== '') {
939 11
            $namedFormula = StringHelper::strToUpper($namedFormula);
940
            // first look for global named formula
941 11
            $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
942
            // then look for local named formula (has priority over global named formula if both names exist)
943 11
            $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
944
        }
945
946 11
        return $returnValue instanceof NamedFormula ? $returnValue : null;
947
    }
948
949 37
    private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName
950
    {
951 37
        if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) {
952 27
            return $this->definedNames[$name];
953
        }
954
955 12
        return null;
956
    }
957
958 37
    private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
959
    {
960
        if (
961 37
            ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
962 37
            && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
963
        ) {
964 8
            return $this->definedNames[$worksheet->getTitle() . '!' . $name];
965
        }
966
967 35
        return null;
968
    }
969
970
    /**
971
     * Get named range.
972
     *
973
     * @param null|Worksheet $worksheet Scope. Use null for global scope
974
     */
975 10085
    public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
976
    {
977 10085
        $returnValue = null;
978
979 10085
        if ($definedName !== '') {
980 10085
            $definedName = StringHelper::strToUpper($definedName);
981
            // first look for global defined name
982 10085
            if (isset($this->definedNames[$definedName])) {
983 124
                $returnValue = $this->definedNames[$definedName];
984
            }
985
986
            // then look for local defined name (has priority over global defined name if both names exist)
987 10085
            if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
988 21
                $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName];
989
            }
990
        }
991
992 10085
        return $returnValue;
993
    }
994
995
    /**
996
     * Remove named range.
997
     *
998
     * @param null|Worksheet $worksheet scope: use null for global scope
999
     *
1000
     * @return $this
1001
     */
1002 5
    public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
1003
    {
1004 5
        if ($this->getNamedRange($namedRange, $worksheet) === null) {
1005 1
            return $this;
1006
        }
1007
1008 4
        return $this->removeDefinedName($namedRange, $worksheet);
1009
    }
1010
1011
    /**
1012
     * Remove named formula.
1013
     *
1014
     * @param null|Worksheet $worksheet scope: use null for global scope
1015
     *
1016
     * @return $this
1017
     */
1018 4
    public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
1019
    {
1020 4
        if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
1021 1
            return $this;
1022
        }
1023
1024 3
        return $this->removeDefinedName($namedFormula, $worksheet);
1025
    }
1026
1027
    /**
1028
     * Remove defined name.
1029
     *
1030
     * @param null|Worksheet $worksheet scope: use null for global scope
1031
     *
1032
     * @return $this
1033
     */
1034 11
    public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
1035
    {
1036 11
        $definedName = StringHelper::strToUpper($definedName);
1037
1038 11
        if ($worksheet === null) {
1039 1
            if (isset($this->definedNames[$definedName])) {
1040 1
                unset($this->definedNames[$definedName]);
1041
            }
1042
        } else {
1043 10
            if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
1044 3
                unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
1045 7
            } elseif (isset($this->definedNames[$definedName])) {
1046 7
                unset($this->definedNames[$definedName]);
1047
            }
1048
        }
1049
1050 11
        return $this;
1051
    }
1052
1053
    /**
1054
     * Get worksheet iterator.
1055
     */
1056 1348
    public function getWorksheetIterator(): Iterator
1057
    {
1058 1348
        return new Iterator($this);
1059
    }
1060
1061
    /**
1062
     * Copy workbook (!= clone!).
1063
     */
1064 1
    public function copy(): self
1065
    {
1066 1
        $filename = File::temporaryFilename();
1067 1
        $writer = new XlsxWriter($this);
1068 1
        $writer->setIncludeCharts(true);
1069 1
        $writer->save($filename);
1070
1071 1
        $reader = new XlsxReader();
1072 1
        $reader->setIncludeCharts(true);
1073 1
        $reloadedSpreadsheet = $reader->load($filename);
1074 1
        unlink($filename);
1075
1076 1
        return $reloadedSpreadsheet;
1077
    }
1078
1079 1
    public function __clone()
1080
    {
1081 1
        throw new Exception(
1082 1
            'Do not use clone on spreadsheet. Use spreadsheet->copy() instead.'
1083 1
        );
1084
    }
1085
1086
    /**
1087
     * Get the workbook collection of cellXfs.
1088
     *
1089
     * @return Style[]
1090
     */
1091 1067
    public function getCellXfCollection(): array
1092
    {
1093 1067
        return $this->cellXfCollection;
1094
    }
1095
1096
    /**
1097
     * Get cellXf by index.
1098
     */
1099 9994
    public function getCellXfByIndex(int $cellStyleIndex): Style
1100
    {
1101 9994
        return $this->cellXfCollection[$cellStyleIndex];
1102
    }
1103
1104 2
    public function getCellXfByIndexOrNull(?int $cellStyleIndex): ?Style
1105
    {
1106 2
        return ($cellStyleIndex === null) ? null : ($this->cellXfCollection[$cellStyleIndex] ?? null);
1107
    }
1108
1109
    /**
1110
     * Get cellXf by hash code.
1111
     *
1112
     * @return false|Style
1113
     */
1114 874
    public function getCellXfByHashCode(string $hashcode): bool|Style
1115
    {
1116 874
        foreach ($this->cellXfCollection as $cellXf) {
1117 874
            if ($cellXf->getHashCode() === $hashcode) {
1118 240
                return $cellXf;
1119
            }
1120
        }
1121
1122 821
        return false;
1123
    }
1124
1125
    /**
1126
     * Check if style exists in style collection.
1127
     */
1128 1
    public function cellXfExists(Style $cellStyleIndex): bool
1129
    {
1130 1
        return in_array($cellStyleIndex, $this->cellXfCollection, true);
1131
    }
1132
1133
    /**
1134
     * Get default style.
1135
     */
1136 974
    public function getDefaultStyle(): Style
1137
    {
1138 974
        if (isset($this->cellXfCollection[0])) {
1139 973
            return $this->cellXfCollection[0];
1140
        }
1141
1142 1
        throw new Exception('No default style found for this workbook');
1143
    }
1144
1145
    /**
1146
     * Add a cellXf to the workbook.
1147
     */
1148 10393
    public function addCellXf(Style $style): void
1149
    {
1150 10393
        $this->cellXfCollection[] = $style;
1151 10393
        $style->setIndex(count($this->cellXfCollection) - 1);
1152
    }
1153
1154
    /**
1155
     * Remove cellXf by index. It is ensured that all cells get their xf index updated.
1156
     *
1157
     * @param int $cellStyleIndex Index to cellXf
1158
     */
1159 754
    public function removeCellXfByIndex(int $cellStyleIndex): void
1160
    {
1161 754
        if ($cellStyleIndex > count($this->cellXfCollection) - 1) {
1162 1
            throw new Exception('CellXf index is out of bounds.');
1163
        }
1164
1165
        // first remove the cellXf
1166 753
        array_splice($this->cellXfCollection, $cellStyleIndex, 1);
1167
1168
        // then update cellXf indexes for cells
1169 753
        foreach ($this->workSheetCollection as $worksheet) {
1170 2
            foreach ($worksheet->getCoordinates(false) as $coordinate) {
1171 1
                $cell = $worksheet->getCell($coordinate);
1172 1
                $xfIndex = $cell->getXfIndex();
1173 1
                if ($xfIndex > $cellStyleIndex) {
1174
                    // decrease xf index by 1
1175 1
                    $cell->setXfIndex($xfIndex - 1);
1176 1
                } elseif ($xfIndex == $cellStyleIndex) {
1177
                    // set to default xf index 0
1178 1
                    $cell->setXfIndex(0);
1179
                }
1180
            }
1181
        }
1182
    }
1183
1184
    /**
1185
     * Get the cellXf supervisor.
1186
     */
1187 10013
    public function getCellXfSupervisor(): Style
1188
    {
1189 10013
        return $this->cellXfSupervisor;
1190
    }
1191
1192
    /**
1193
     * Get the workbook collection of cellStyleXfs.
1194
     *
1195
     * @return Style[]
1196
     */
1197 1
    public function getCellStyleXfCollection(): array
1198
    {
1199 1
        return $this->cellStyleXfCollection;
1200
    }
1201
1202
    /**
1203
     * Get cellStyleXf by index.
1204
     *
1205
     * @param int $cellStyleIndex Index to cellXf
1206
     */
1207 1
    public function getCellStyleXfByIndex(int $cellStyleIndex): Style
1208
    {
1209 1
        return $this->cellStyleXfCollection[$cellStyleIndex];
1210
    }
1211
1212
    /**
1213
     * Get cellStyleXf by hash code.
1214
     *
1215
     * @return false|Style
1216
     */
1217 1
    public function getCellStyleXfByHashCode(string $hashcode): bool|Style
1218
    {
1219 1
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1220 1
            if ($cellStyleXf->getHashCode() === $hashcode) {
1221 1
                return $cellStyleXf;
1222
            }
1223
        }
1224
1225 1
        return false;
1226
    }
1227
1228
    /**
1229
     * Add a cellStyleXf to the workbook.
1230
     */
1231 10393
    public function addCellStyleXf(Style $style): void
1232
    {
1233 10393
        $this->cellStyleXfCollection[] = $style;
1234 10393
        $style->setIndex(count($this->cellStyleXfCollection) - 1);
1235
    }
1236
1237
    /**
1238
     * Remove cellStyleXf by index.
1239
     *
1240
     * @param int $cellStyleIndex Index to cellXf
1241
     */
1242 751
    public function removeCellStyleXfByIndex(int $cellStyleIndex): void
1243
    {
1244 751
        if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) {
1245 1
            throw new Exception('CellStyleXf index is out of bounds.');
1246
        }
1247 750
        array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1);
1248
    }
1249
1250
    /**
1251
     * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
1252
     * and columns in the workbook.
1253
     */
1254 978
    public function garbageCollect(): void
1255
    {
1256
        // how many references are there to each cellXf ?
1257 978
        $countReferencesCellXf = [];
1258 978
        foreach ($this->cellXfCollection as $index => $cellXf) {
1259 978
            $countReferencesCellXf[$index] = 0;
1260
        }
1261
1262 978
        foreach ($this->getWorksheetIterator() as $sheet) {
1263
            // from cells
1264 978
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1265 951
                $cell = $sheet->getCell($coordinate);
1266 951
                ++$countReferencesCellXf[$cell->getXfIndex()];
1267
            }
1268
1269
            // from row dimensions
1270 978
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1271 83
                if ($rowDimension->getXfIndex() !== null) {
1272 11
                    ++$countReferencesCellXf[$rowDimension->getXfIndex()];
1273
                }
1274
            }
1275
1276
            // from column dimensions
1277 978
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1278 134
                ++$countReferencesCellXf[$columnDimension->getXfIndex()];
1279
            }
1280
        }
1281
1282
        // remove cellXfs without references and create mapping so we can update xfIndex
1283
        // for all cells and columns
1284 978
        $countNeededCellXfs = 0;
1285 978
        $map = [];
1286 978
        foreach ($this->cellXfCollection as $index => $cellXf) {
1287 978
            if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
1288 978
                ++$countNeededCellXfs;
1289
            } else {
1290 35
                unset($this->cellXfCollection[$index]);
1291
            }
1292 978
            $map[$index] = $countNeededCellXfs - 1;
1293
        }
1294 978
        $this->cellXfCollection = array_values($this->cellXfCollection);
1295
1296
        // update the index for all cellXfs
1297 978
        foreach ($this->cellXfCollection as $i => $cellXf) {
1298 978
            $cellXf->setIndex($i);
1299
        }
1300
1301
        // make sure there is always at least one cellXf (there should be)
1302 978
        if (empty($this->cellXfCollection)) {
1303
            $this->cellXfCollection[] = new Style();
1304
        }
1305
1306
        // update the xfIndex for all cells, row dimensions, column dimensions
1307 978
        foreach ($this->getWorksheetIterator() as $sheet) {
1308
            // for all cells
1309 978
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1310 951
                $cell = $sheet->getCell($coordinate);
1311 951
                $cell->setXfIndex($map[$cell->getXfIndex()]);
1312
            }
1313
1314
            // for all row dimensions
1315 978
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1316 83
                if ($rowDimension->getXfIndex() !== null) {
1317 11
                    $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]);
1318
                }
1319
            }
1320
1321
            // for all column dimensions
1322 978
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1323 134
                $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]);
1324
            }
1325
1326
            // also do garbage collection for all the sheets
1327 978
            $sheet->garbageCollect();
1328
        }
1329
    }
1330
1331
    /**
1332
     * Return the unique ID value assigned to this spreadsheet workbook.
1333
     */
1334
    public function getID(): string
1335
    {
1336
        return $this->uniqueID;
1337
    }
1338
1339
    /**
1340
     * Get the visibility of the horizonal scroll bar in the application.
1341
     *
1342
     * @return bool True if horizonal scroll bar is visible
1343
     */
1344 365
    public function getShowHorizontalScroll(): bool
1345
    {
1346 365
        return $this->showHorizontalScroll;
1347
    }
1348
1349
    /**
1350
     * Set the visibility of the horizonal scroll bar in the application.
1351
     *
1352
     * @param bool $showHorizontalScroll True if horizonal scroll bar is visible
1353
     */
1354 249
    public function setShowHorizontalScroll(bool $showHorizontalScroll): void
1355
    {
1356 249
        $this->showHorizontalScroll = (bool) $showHorizontalScroll;
1357
    }
1358
1359
    /**
1360
     * Get the visibility of the vertical scroll bar in the application.
1361
     *
1362
     * @return bool True if vertical scroll bar is visible
1363
     */
1364 365
    public function getShowVerticalScroll(): bool
1365
    {
1366 365
        return $this->showVerticalScroll;
1367
    }
1368
1369
    /**
1370
     * Set the visibility of the vertical scroll bar in the application.
1371
     *
1372
     * @param bool $showVerticalScroll True if vertical scroll bar is visible
1373
     */
1374 249
    public function setShowVerticalScroll(bool $showVerticalScroll): void
1375
    {
1376 249
        $this->showVerticalScroll = (bool) $showVerticalScroll;
1377
    }
1378
1379
    /**
1380
     * Get the visibility of the sheet tabs in the application.
1381
     *
1382
     * @return bool True if the sheet tabs are visible
1383
     */
1384 365
    public function getShowSheetTabs(): bool
1385
    {
1386 365
        return $this->showSheetTabs;
1387
    }
1388
1389
    /**
1390
     * Set the visibility of the sheet tabs  in the application.
1391
     *
1392
     * @param bool $showSheetTabs True if sheet tabs are visible
1393
     */
1394 249
    public function setShowSheetTabs(bool $showSheetTabs): void
1395
    {
1396 249
        $this->showSheetTabs = (bool) $showSheetTabs;
1397
    }
1398
1399
    /**
1400
     * Return whether the workbook window is minimized.
1401
     *
1402
     * @return bool true if workbook window is minimized
1403
     */
1404 365
    public function getMinimized(): bool
1405
    {
1406 365
        return $this->minimized;
1407
    }
1408
1409
    /**
1410
     * Set whether the workbook window is minimized.
1411
     *
1412
     * @param bool $minimized true if workbook window is minimized
1413
     */
1414 243
    public function setMinimized(bool $minimized): void
1415
    {
1416 243
        $this->minimized = (bool) $minimized;
1417
    }
1418
1419
    /**
1420
     * Return whether to group dates when presenting the user with
1421
     * filtering optiomd in the user interface.
1422
     *
1423
     * @return bool true if workbook window is minimized
1424
     */
1425 365
    public function getAutoFilterDateGrouping(): bool
1426
    {
1427 365
        return $this->autoFilterDateGrouping;
1428
    }
1429
1430
    /**
1431
     * Set whether to group dates when presenting the user with
1432
     * filtering optiomd in the user interface.
1433
     *
1434
     * @param bool $autoFilterDateGrouping true if workbook window is minimized
1435
     */
1436 243
    public function setAutoFilterDateGrouping(bool $autoFilterDateGrouping): void
1437
    {
1438 243
        $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping;
1439
    }
1440
1441
    /**
1442
     * Return the first sheet in the book view.
1443
     *
1444
     * @return int First sheet in book view
1445
     */
1446 365
    public function getFirstSheetIndex(): int
1447
    {
1448 365
        return $this->firstSheetIndex;
1449
    }
1450
1451
    /**
1452
     * Set the first sheet in the book view.
1453
     *
1454
     * @param int $firstSheetIndex First sheet in book view
1455
     */
1456 251
    public function setFirstSheetIndex(int $firstSheetIndex): void
1457
    {
1458 251
        if ($firstSheetIndex >= 0) {
1459 250
            $this->firstSheetIndex = (int) $firstSheetIndex;
1460
        } else {
1461 1
            throw new Exception('First sheet index must be a positive integer.');
1462
        }
1463
    }
1464
1465
    /**
1466
     * Return the visibility status of the workbook.
1467
     *
1468
     * This may be one of the following three values:
1469
     * - visibile
1470
     *
1471
     * @return string Visible status
1472
     */
1473 366
    public function getVisibility(): string
1474
    {
1475 366
        return $this->visibility;
1476
    }
1477
1478
    /**
1479
     * Set the visibility status of the workbook.
1480
     *
1481
     * Valid values are:
1482
     *  - 'visible' (self::VISIBILITY_VISIBLE):
1483
     *       Workbook window is visible
1484
     *  - 'hidden' (self::VISIBILITY_HIDDEN):
1485
     *       Workbook window is hidden, but can be shown by the user
1486
     *       via the user interface
1487
     *  - 'veryHidden' (self::VISIBILITY_VERY_HIDDEN):
1488
     *       Workbook window is hidden and cannot be shown in the
1489
     *       user interface.
1490
     *
1491
     * @param null|string $visibility visibility status of the workbook
1492
     */
1493 244
    public function setVisibility(?string $visibility): void
1494
    {
1495 244
        if ($visibility === null) {
1496 1
            $visibility = self::VISIBILITY_VISIBLE;
1497
        }
1498
1499 244
        if (in_array($visibility, self::WORKBOOK_VIEW_VISIBILITY_VALUES)) {
1500 244
            $this->visibility = $visibility;
1501
        } else {
1502 1
            throw new Exception('Invalid visibility value.');
1503
        }
1504
    }
1505
1506
    /**
1507
     * Get the ratio between the workbook tabs bar and the horizontal scroll bar.
1508
     * TabRatio is assumed to be out of 1000 of the horizontal window width.
1509
     *
1510
     * @return int Ratio between the workbook tabs bar and the horizontal scroll bar
1511
     */
1512 365
    public function getTabRatio(): int
1513
    {
1514 365
        return $this->tabRatio;
1515
    }
1516
1517
    /**
1518
     * Set the ratio between the workbook tabs bar and the horizontal scroll bar
1519
     * TabRatio is assumed to be out of 1000 of the horizontal window width.
1520
     *
1521
     * @param int $tabRatio Ratio between the tabs bar and the horizontal scroll bar
1522
     */
1523 253
    public function setTabRatio(int $tabRatio): void
1524
    {
1525 253
        if ($tabRatio >= 0 && $tabRatio <= 1000) {
1526 252
            $this->tabRatio = (int) $tabRatio;
1527
        } else {
1528 1
            throw new Exception('Tab ratio must be between 0 and 1000.');
1529
        }
1530
    }
1531
1532 2
    public function reevaluateAutoFilters(bool $resetToMax): void
1533
    {
1534 2
        foreach ($this->workSheetCollection as $sheet) {
1535 2
            $filter = $sheet->getAutoFilter();
1536 2
            if (!empty($filter->getRange())) {
1537 2
                if ($resetToMax) {
1538 1
                    $filter->setRangeToMaxRow();
1539
                }
1540 2
                $filter->showHideRows();
1541
            }
1542
        }
1543
    }
1544
1545
    /**
1546
     * @throws Exception
1547
     */
1548 2
    public function __serialize(): array
1549
    {
1550 2
        throw new Exception('Spreadsheet objects cannot be serialized');
1551
    }
1552
1553
    /**
1554
     * @throws Exception
1555
     */
1556 1
    public function jsonSerialize(): mixed
1557
    {
1558 1
        throw new Exception('Spreadsheet objects cannot be json encoded');
1559
    }
1560
1561 1
    public function resetThemeFonts(): void
1562
    {
1563 1
        $majorFontLatin = $this->theme->getMajorFontLatin();
1564 1
        $minorFontLatin = $this->theme->getMinorFontLatin();
1565 1
        foreach ($this->cellXfCollection as $cellStyleXf) {
1566 1
            $scheme = $cellStyleXf->getFont()->getScheme();
1567 1
            if ($scheme === 'major') {
1568 1
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1569 1
            } elseif ($scheme === 'minor') {
1570 1
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1571
            }
1572
        }
1573 1
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1574 1
            $scheme = $cellStyleXf->getFont()->getScheme();
1575 1
            if ($scheme === 'major') {
1576
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1577 1
            } elseif ($scheme === 'minor') {
1578 1
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1579
            }
1580
        }
1581
    }
1582
1583 36
    public function getTableByName(string $tableName): ?Table
1584
    {
1585 36
        $table = null;
1586 36
        foreach ($this->workSheetCollection as $sheet) {
1587 36
            $table = $sheet->getTableByName($tableName);
1588 36
            if ($table !== null) {
1589 5
                break;
1590
            }
1591
        }
1592
1593 36
        return $table;
1594
    }
1595
1596
    /**
1597
     * @return bool Success or failure
1598
     */
1599 746
    public function setExcelCalendar(int $baseYear): bool
1600
    {
1601 746
        if (($baseYear === Date::CALENDAR_WINDOWS_1900) || ($baseYear === Date::CALENDAR_MAC_1904)) {
1602 746
            $this->excelCalendar = $baseYear;
1603
1604 746
            return true;
1605
        }
1606
1607
        return false;
1608
    }
1609
1610
    /**
1611
     * @return int Excel base date (1900 or 1904)
1612
     */
1613 8352
    public function getExcelCalendar(): int
1614
    {
1615 8352
        return $this->excelCalendar;
1616
    }
1617
1618 2
    public function deleteLegacyDrawing(Worksheet $worksheet): void
1619
    {
1620 2
        unset($this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing']);
1621
    }
1622
1623 3
    public function getLegacyDrawing(Worksheet $worksheet): ?string
1624
    {
1625 3
        return $this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'] ?? null;
1626
    }
1627
1628 9555
    public function getValueBinder(): ?IValueBinder
1629
    {
1630 9555
        return $this->valueBinder;
1631
    }
1632
1633 1502
    public function setValueBinder(?IValueBinder $valueBinder): self
1634
    {
1635 1502
        $this->valueBinder = $valueBinder;
1636
1637 1502
        return $this;
1638
    }
1639
1640
    /**
1641
     * All the PDF writers treat charts as if they occupy a single cell.
1642
     * This will be better most of the time.
1643
     * It is not needed for any other output type.
1644
     * It changes the contents of the spreadsheet, so you might
1645
     * be better off cloning the spreadsheet and then using
1646
     * this method on, and then writing, the clone.
1647
     */
1648 1
    public function mergeChartCellsForPdf(): void
1649
    {
1650 1
        foreach ($this->workSheetCollection as $worksheet) {
1651 1
            foreach ($worksheet->getChartCollection() as $chart) {
1652 1
                $br = $chart->getBottomRightCell();
1653 1
                $tl = $chart->getTopLeftCell();
1654 1
                if ($br !== '' && $br !== $tl) {
1655 1
                    if (!$worksheet->cellExists($br)) {
1656 1
                        $worksheet->getCell($br)->setValue(' ');
1657
                    }
1658 1
                    $worksheet->mergeCells("$tl:$br");
1659
                }
1660
            }
1661
        }
1662
    }
1663
1664
    /**
1665
     * All the PDF writers do better with drawings than charts.
1666
     * This will be better some of the time.
1667
     * It is not needed for any other output type.
1668
     * It changes the contents of the spreadsheet, so you might
1669
     * be better off cloning the spreadsheet and then using
1670
     * this method on, and then writing, the clone.
1671
     */
1672 1
    public function mergeDrawingCellsForPdf(): void
1673
    {
1674 1
        foreach ($this->workSheetCollection as $worksheet) {
1675 1
            foreach ($worksheet->getDrawingCollection() as $drawing) {
1676 1
                $br = $drawing->getCoordinates2();
1677 1
                $tl = $drawing->getCoordinates();
1678 1
                if ($br !== '' && $br !== $tl) {
1679 1
                    if (!$worksheet->cellExists($br)) {
1680 1
                        $worksheet->getCell($br)->setValue(' ');
1681
                    }
1682 1
                    $worksheet->mergeCells("$tl:$br");
1683
                }
1684
            }
1685
        }
1686
    }
1687
}
1688