Passed
Pull Request — master (#4315)
by Owen
30:52 queued 17:38
created

Spreadsheet::duplicateWorksheetByTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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