Spreadsheet::getSheetByName()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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