Spreadsheet::getSheetNames()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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