Passed
Pull Request — master (#4315)
by Owen
12:23
created

Spreadsheet::duplicateWorksheetByTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 1
cts 1
cp 1
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 744
    public function getTheme(): Theme
180
    {
181 744
        return $this->theme;
182
    }
183
184
    /**
185
     * The workbook has macros ?
186
     */
187 403
    public function hasMacros(): bool
188
    {
189 403
        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 364
    public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here...
273
    {
274 364
        $returnData = null;
275 364
        $what = strtolower($what);
276
        switch ($what) {
277 364
            case 'all':
278 2
                $returnData = $this->ribbonXMLData;
279
280 2
                break;
281 364
            case 'target':
282 2
            case 'data':
283 364
                if (is_array($this->ribbonXMLData)) {
284 2
                    $returnData = $this->ribbonXMLData[$what];
285
                }
286
287 364
                break;
288
        }
289
290 364
        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 404
    public function getUnparsedLoadedData(): array
312
    {
313 404
        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 637
    public function setUnparsedLoadedData(array $unparsedLoadedData): void
323
    {
324 637
        $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 364
    public function hasRibbon(): bool
365
    {
366 364
        return $this->ribbonXMLData !== null;
367
    }
368
369
    /**
370
     * This workbook have additionnal object for the ribbon ?
371
     */
372 364
    public function hasRibbonBinObjects(): bool
373
    {
374 364
        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 10374
    public function sheetCodeNameExists(string $codeName): bool
383
    {
384 10374
        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 10374
    public function getSheetByCodeName(string $codeName): ?Worksheet
393
    {
394 10374
        $worksheetCount = count($this->workSheetCollection);
395 10374
        for ($i = 0; $i < $worksheetCount; ++$i) {
396 705
            if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
397 671
                return $this->workSheetCollection[$i];
398
            }
399
        }
400
401 10374
        return null;
402
    }
403
404
    /**
405
     * Create a new PhpSpreadsheet with one Worksheet.
406
     */
407 10374
    public function __construct()
408
    {
409 10374
        $this->uniqueID = uniqid('', true);
410 10374
        $this->calculationEngine = new Calculation($this);
411 10374
        $this->theme = new Theme();
412
413
        // Initialise worksheet collection and add one worksheet
414 10374
        $this->workSheetCollection = [];
415 10374
        $this->workSheetCollection[] = new Worksheet($this);
416 10374
        $this->activeSheetIndex = 0;
417
418
        // Create document properties
419 10374
        $this->properties = new Properties();
420
421
        // Create document security
422 10374
        $this->security = new Security();
423
424
        // Set defined names
425 10374
        $this->definedNames = [];
426
427
        // Create the cellXf supervisor
428 10374
        $this->cellXfSupervisor = new Style(true);
429 10374
        $this->cellXfSupervisor->bindParent($this);
430
431
        // Create the default style
432 10374
        $this->addCellXf(new Style());
433 10374
        $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 9027
    public function disconnectWorksheets(): void
453
    {
454 9027
        foreach ($this->workSheetCollection as $worksheet) {
455 9024
            $worksheet->disconnectCells();
456 9024
            unset($worksheet);
457
        }
458 9027
        $this->workSheetCollection = [];
459
    }
460
461
    /**
462
     * Return the calculation engine for this worksheet.
463
     */
464 9488
    public function getCalculationEngine(): ?Calculation
465
    {
466 9488
        return $this->calculationEngine;
467
    }
468
469
    /**
470
     * Get properties.
471
     */
472 1541
    public function getProperties(): Properties
473
    {
474 1541
        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 377
    public function getSecurity(): Security
489
    {
490 377
        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 10307
    public function getActiveSheet(): Worksheet
505
    {
506 10307
        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 1176
    public function createSheet(?int $sheetIndex = null): Worksheet
515
    {
516 1176
        $newSheet = new Worksheet($this);
517 1176
        $this->addSheet($newSheet, $sheetIndex, true);
518
519 1176
        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 1748
    public function sheetNameExists(string $worksheetName): bool
528
    {
529 1748
        return $this->getSheetByName($worksheetName) !== null;
530
    }
531
532
    public function duplicateWorksheetByTitle(string $title): Worksheet
533
    {
534
        $original = $this->getSheetByNameOrThrow($title);
535
        $index = $this->getIndex($original) + 1;
536
        $clone = clone $original;
537
538 1267
        return $this->addSheet($clone, $index, true);
539
    }
540 1267
541 1176
    /**
542 1176
     * Add sheet.
543 157
     *
544 157
     * @param Worksheet $worksheet The worksheet to add
545 157
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
546 27
     */
547 27
    public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet
548
    {
549 157
        if ($retitleIfNeeded) {
550
            $title = $worksheet->getTitle();
551
            if ($this->sheetNameExists($title)) {
552 1267
                $i = 1;
553 2
                $newTitle = "$title $i";
554 2
                while ($this->sheetNameExists($newTitle)) {
555 2
                    ++$i;
556
                    $newTitle = "$title $i";
557
                }
558 1267
                $worksheet->setTitle($newTitle);
559 1234
            }
560 858
        }
561
        if ($this->sheetNameExists($worksheet->getTitle())) {
562 1234
            throw new Exception(
563
                "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
564
            );
565 37
        }
566 37
567 37
        if ($sheetIndex === null) {
568 37
            if ($this->activeSheetIndex < 0) {
569 37
                $this->activeSheetIndex = 0;
570 37
            }
571
            $this->workSheetCollection[] = $worksheet;
572
        } else {
573 37
            // Insert the sheet at the requested index
574 30
            array_splice(
575
                $this->workSheetCollection,
576 37
                $sheetIndex,
577 3
                0,
578
                [$worksheet]
579
            );
580
581 1267
            // Adjust active sheet index if necessary
582 51
            if ($this->activeSheetIndex >= $sheetIndex) {
583
                ++$this->activeSheetIndex;
584
            }
585 1267
            if ($this->activeSheetIndex < 0) {
586
                $this->activeSheetIndex = 0;
587
            }
588
        }
589
590
        if ($worksheet->getParent() === null) {
591
            $worksheet->rebindParent($this);
592
        }
593 898
594
        return $worksheet;
595 898
    }
596 898
597 1
    /**
598 1
     * Remove sheet by index.
599 1
     *
600
     * @param int $sheetIndex Index position of the worksheet to remove
601 897
     */
602
    public function removeSheetByIndex(int $sheetIndex): void
603
    {
604
        $numSheets = count($this->workSheetCollection);
605 897
        if ($sheetIndex > $numSheets - 1) {
606 897
            throw new Exception(
607
                "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
608 895
            );
609
        }
610
        array_splice($this->workSheetCollection, $sheetIndex, 1);
611
612
        // Adjust active sheet index if necessary
613
        if (
614
            ($this->activeSheetIndex >= $sheetIndex)
615
            && ($this->activeSheetIndex > 0 || $numSheets <= 1)
616
        ) {
617 10312
            --$this->activeSheetIndex;
618
        }
619 10312
    }
620 1
621
    /**
622 1
     * Get sheet by index.
623 1
     *
624 1
     * @param int $sheetIndex Sheet index
625
     */
626
    public function getSheet(int $sheetIndex): Worksheet
627 10312
    {
628
        if (!isset($this->workSheetCollection[$sheetIndex])) {
629
            $numSheets = $this->getSheetCount();
630
631
            throw new Exception(
632
                "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
633
            );
634
        }
635 157
636
        return $this->workSheetCollection[$sheetIndex];
637 157
    }
638
639
    /**
640
     * Get all sheets.
641
     *
642
     * @return Worksheet[]
643
     */
644
    public function getAllSheets(): array
645 9341
    {
646
        return $this->workSheetCollection;
647 9341
    }
648 9341
649 9030
    /**
650 8451
     * Get sheet by name.
651
     *
652
     * @param string $worksheetName Sheet name
653
     */
654 1760
    public function getSheetByName(string $worksheetName): ?Worksheet
655
    {
656
        $worksheetCount = count($this->workSheetCollection);
657
        for ($i = 0; $i < $worksheetCount; ++$i) {
658
            if (strcasecmp($this->workSheetCollection[$i]->getTitle(), trim($worksheetName, "'")) === 0) {
659
                return $this->workSheetCollection[$i];
660 231
            }
661
        }
662 231
663 231
        return null;
664 1
    }
665
666
    /**
667 230
     * Get sheet by name, throwing exception if not found.
668
     */
669
    public function getSheetByNameOrThrow(string $worksheetName): Worksheet
670
    {
671
        $worksheet = $this->getSheetByName($worksheetName);
672
        if ($worksheet === null) {
673
            throw new Exception("Sheet $worksheetName does not exist.");
674
        }
675 10374
676
        return $worksheet;
677 10374
    }
678 10374
679 10167
    /**
680 10155
     * Get index for sheet.
681
     *
682
     * @return int index
683 10374
     */
684 10374
    public function getIndex(Worksheet $worksheet, bool $noThrow = false): int
685
    {
686
        $wsHash = $worksheet->getHashInt();
687 3
        foreach ($this->workSheetCollection as $key => $value) {
688
            if ($value->getHashInt() === $wsHash) {
689
                return $key;
690
            }
691
        }
692
        if ($noThrow) {
693
            return -1;
694
        }
695
696
        throw new Exception('Sheet does not exist.');
697
    }
698 1
699
    /**
700 1
     * Set index for sheet by sheet name.
701 1
     *
702 1
     * @param string $worksheetName Sheet name to modify index for
703 1
     * @param int $newIndexPosition New index for the sheet
704 1
     *
705 1
     * @return int New sheet index
706 1
     */
707 1
    public function setIndexByName(string $worksheetName, int $newIndexPosition): int
708 1
    {
709 1
        $oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName));
710 1
        $worksheet = array_splice(
711 1
            $this->workSheetCollection,
712
            $oldIndex,
713 1
            1
714
        );
715
        array_splice(
716
            $this->workSheetCollection,
717
            $newIndexPosition,
718
            0,
719 1518
            $worksheet
720
        );
721 1518
722
        return $newIndexPosition;
723
    }
724
725
    /**
726
     * Get sheet count.
727
     */
728
    public function getSheetCount(): int
729 10042
    {
730
        return count($this->workSheetCollection);
731 10042
    }
732
733
    /**
734
     * Get active sheet index.
735
     *
736
     * @return int Active sheet index
737
     */
738
    public function getActiveSheetIndex(): int
739 10111
    {
740
        return $this->activeSheetIndex;
741 10111
    }
742
743 10111
    /**
744 6
     * Set active sheet index.
745 6
     *
746 6
     * @param int $worksheetIndex Active sheet index
747
     */
748 10105
    public function setActiveSheetIndex(int $worksheetIndex): Worksheet
749
    {
750 10105
        $numSheets = count($this->workSheetCollection);
751
752
        if ($worksheetIndex > $numSheets - 1) {
753
            throw new Exception(
754
                "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
755
            );
756
        }
757
        $this->activeSheetIndex = $worksheetIndex;
758 94
759
        return $this->getActiveSheet();
760 94
    }
761 92
762
    /**
763 92
     * Set active sheet index by name.
764
     *
765
     * @param string $worksheetName Sheet title
766 2
     */
767
    public function setActiveSheetIndexByName(string $worksheetName): Worksheet
768
    {
769
        if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
770
            $this->setActiveSheetIndex($this->getIndex($worksheet));
771
772
            return $worksheet;
773
        }
774 10
775
        throw new Exception('Workbook does not contain sheet:' . $worksheetName);
776 10
    }
777 10
778 10
    /**
779 10
     * Get sheet names.
780
     *
781
     * @return string[]
782 10
     */
783
    public function getSheetNames(): array
784
    {
785
        $returnValue = [];
786
        $worksheetCount = $this->getSheetCount();
787
        for ($i = 0; $i < $worksheetCount; ++$i) {
788
            $returnValue[] = $this->getSheet($i)->getTitle();
789
        }
790
791 5
        return $returnValue;
792
    }
793 5
794 1
    /**
795
     * Add external sheet.
796
     *
797
     * @param Worksheet $worksheet External sheet to add
798 4
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
799
     */
800
    public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet
801 4
    {
802 4
        if ($this->sheetNameExists($worksheet->getTitle())) {
803
            throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
804
        }
805
806 4
        // count how many cellXfs there are in this workbook currently, we will need this below
807
        $countCellXfs = count($this->cellXfCollection);
808
809 4
        // 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 1
817
        // update the cellXfs
818
        foreach ($worksheet->getCoordinates(false) as $coordinate) {
819
            $cell = $worksheet->getCell($coordinate);
820 4
            $cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
821 1
        }
822 1
823 1
        // update the column dimensions Xfs
824
        foreach ($worksheet->getColumnDimensions() as $columnDimension) {
825
            $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs);
826
        }
827 4
828
        // update the row dimensions Xfs
829
        foreach ($worksheet->getRowDimensions() as $rowDimension) {
830
            $xfIndex = $rowDimension->getXfIndex();
831
            if ($xfIndex !== null) {
832
                $rowDimension->setXfIndex($xfIndex + $countCellXfs);
833
            }
834
        }
835 9
836
        return $this->addSheet($worksheet, $sheetIndex);
837 9
    }
838 9
839 9
    /**
840 9
     * Get an array of all Named Ranges.
841
     *
842
     * @return DefinedName[]
843
     */
844
    public function getNamedRanges(): array
845
    {
846
        return array_filter(
847
            $this->definedNames,
848 15
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE
849
        );
850 15
    }
851 15
852 15
    /**
853 15
     * Get an array of all Named Formulae.
854
     *
855
     * @return DefinedName[]
856
     */
857
    public function getNamedFormulae(): array
858
    {
859
        return array_filter(
860
            $this->definedNames,
861 549
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA
862
        );
863 549
    }
864
865
    /**
866
     * Get an array of all Defined Names (both named ranges and named formulae).
867
     *
868
     * @return DefinedName[]
869
     */
870 305
    public function getDefinedNames(): array
871
    {
872 305
        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 12
    public function addNamedRange(NamedRange $namedRange): void
880
    {
881 12
        $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 423
    public function addNamedFormula(NamedFormula $namedFormula): void
889
    {
890 423
        $this->addDefinedName($namedFormula);
891 423
    }
892
893 410
    /**
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 121
     */
897
    public function addDefinedName(DefinedName $definedName): void
898
    {
899
        $upperCaseName = StringHelper::strToUpper($definedName->getName());
900
        if ($definedName->getScope() == null) {
901
            // global scope
902
            $this->definedNames[$upperCaseName] = $definedName;
903
        } else {
904
            // local scope
905 26
            $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName;
906
        }
907 26
    }
908
909 26
    /**
910 26
     * Get named range.
911
     *
912 26
     * @param null|Worksheet $worksheet Scope. Use null for global scope
913
     */
914 26
    public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
915
    {
916
        $returnValue = null;
917 26
918
        if ($namedRange !== '') {
919
            $namedRange = StringHelper::strToUpper($namedRange);
920
            // first look for global named range
921
            $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
            $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
924
        }
925 11
926
        return $returnValue instanceof NamedRange ? $returnValue : null;
927 11
    }
928
929 11
    /**
930 11
     * Get named formula.
931
     *
932 11
     * @param null|Worksheet $worksheet Scope. Use null for global scope
933
     */
934 11
    public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
935
    {
936
        $returnValue = null;
937 11
938
        if ($namedFormula !== '') {
939
            $namedFormula = StringHelper::strToUpper($namedFormula);
940 37
            // first look for global named formula
941
            $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
942 37
            // then look for local named formula (has priority over global named formula if both names exist)
943 27
            $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
944
        }
945
946 12
        return $returnValue instanceof NamedFormula ? $returnValue : null;
947
    }
948
949 37
    private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName
950
    {
951
        if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) {
952 37
            return $this->definedNames[$name];
953 37
        }
954
955 8
        return null;
956
    }
957
958 35
    private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
959
    {
960
        if (
961
            ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
962
            && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
963
        ) {
964
            return $this->definedNames[$worksheet->getTitle() . '!' . $name];
965
        }
966 10072
967
        return null;
968 10072
    }
969
970 10072
    /**
971 10072
     * Get named range.
972
     *
973 10072
     * @param null|Worksheet $worksheet Scope. Use null for global scope
974 124
     */
975
    public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
976
    {
977
        $returnValue = null;
978 10072
979 21
        if ($definedName !== '') {
980
            $definedName = StringHelper::strToUpper($definedName);
981
            // first look for global defined name
982
            if (isset($this->definedNames[$definedName])) {
983 10072
                $returnValue = $this->definedNames[$definedName];
984
            }
985
986
            // then look for local defined name (has priority over global defined name if both names exist)
987
            if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
988
                $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName];
989
            }
990
        }
991
992
        return $returnValue;
993 5
    }
994
995 5
    /**
996 1
     * Remove named range.
997
     *
998
     * @param null|Worksheet $worksheet scope: use null for global scope
999 4
     *
1000
     * @return $this
1001
     */
1002
    public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
1003
    {
1004
        if ($this->getNamedRange($namedRange, $worksheet) === null) {
1005
            return $this;
1006
        }
1007
1008
        return $this->removeDefinedName($namedRange, $worksheet);
1009 4
    }
1010
1011 4
    /**
1012 1
     * Remove named formula.
1013
     *
1014
     * @param null|Worksheet $worksheet scope: use null for global scope
1015 3
     *
1016
     * @return $this
1017
     */
1018
    public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
1019
    {
1020
        if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
1021
            return $this;
1022
        }
1023
1024
        return $this->removeDefinedName($namedFormula, $worksheet);
1025 11
    }
1026
1027 11
    /**
1028
     * Remove defined name.
1029 11
     *
1030 1
     * @param null|Worksheet $worksheet scope: use null for global scope
1031 1
     *
1032
     * @return $this
1033
     */
1034 10
    public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
1035 3
    {
1036 7
        $definedName = StringHelper::strToUpper($definedName);
1037 7
1038
        if ($worksheet === null) {
1039
            if (isset($this->definedNames[$definedName])) {
1040
                unset($this->definedNames[$definedName]);
1041 11
            }
1042
        } else {
1043
            if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
1044
                unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
1045
            } elseif (isset($this->definedNames[$definedName])) {
1046
                unset($this->definedNames[$definedName]);
1047 1337
            }
1048
        }
1049 1337
1050
        return $this;
1051
    }
1052
1053
    /**
1054
     * Get worksheet iterator.
1055 1
     */
1056
    public function getWorksheetIterator(): Iterator
1057 1
    {
1058 1
        return new Iterator($this);
1059 1
    }
1060 1
1061
    /**
1062 1
     * Copy workbook (!= clone!).
1063 1
     */
1064 1
    public function copy(): self
1065 1
    {
1066
        $filename = File::temporaryFilename();
1067 1
        $writer = new XlsxWriter($this);
1068
        $writer->setIncludeCharts(true);
1069
        $writer->save($filename);
1070 1
1071
        $reader = new XlsxReader();
1072 1
        $reader->setIncludeCharts(true);
1073 1
        $reloadedSpreadsheet = $reader->load($filename);
1074 1
        unlink($filename);
1075
1076
        return $reloadedSpreadsheet;
1077
    }
1078
1079
    public function __clone()
1080
    {
1081
        throw new Exception(
1082 1057
            'Do not use clone on spreadsheet. Use spreadsheet->copy() instead.'
1083
        );
1084 1057
    }
1085
1086
    /**
1087
     * Get the workbook collection of cellXfs.
1088
     *
1089
     * @return Style[]
1090 9981
     */
1091
    public function getCellXfCollection(): array
1092 9981
    {
1093
        return $this->cellXfCollection;
1094
    }
1095
1096
    /**
1097
     * Get cellXf by index.
1098
     */
1099
    public function getCellXfByIndex(int $cellStyleIndex): Style
1100 866
    {
1101
        return $this->cellXfCollection[$cellStyleIndex];
1102 866
    }
1103 866
1104 235
    /**
1105
     * Get cellXf by hash code.
1106
     *
1107
     * @return false|Style
1108 814
     */
1109
    public function getCellXfByHashCode(string $hashcode): bool|Style
1110
    {
1111
        foreach ($this->cellXfCollection as $cellXf) {
1112
            if ($cellXf->getHashCode() === $hashcode) {
1113
                return $cellXf;
1114 1
            }
1115
        }
1116 1
1117
        return false;
1118
    }
1119
1120
    /**
1121
     * Check if style exists in style collection.
1122 965
     */
1123
    public function cellXfExists(Style $cellStyleIndex): bool
1124 965
    {
1125 964
        return in_array($cellStyleIndex, $this->cellXfCollection, true);
1126
    }
1127
1128 1
    /**
1129
     * Get default style.
1130
     */
1131
    public function getDefaultStyle(): Style
1132
    {
1133
        if (isset($this->cellXfCollection[0])) {
1134 10374
            return $this->cellXfCollection[0];
1135
        }
1136 10374
1137 10374
        throw new Exception('No default style found for this workbook');
1138
    }
1139
1140
    /**
1141
     * Add a cellXf to the workbook.
1142
     */
1143
    public function addCellXf(Style $style): void
1144
    {
1145 753
        $this->cellXfCollection[] = $style;
1146
        $style->setIndex(count($this->cellXfCollection) - 1);
1147 753
    }
1148 1
1149
    /**
1150
     * Remove cellXf by index. It is ensured that all cells get their xf index updated.
1151
     *
1152 752
     * @param int $cellStyleIndex Index to cellXf
1153
     */
1154
    public function removeCellXfByIndex(int $cellStyleIndex): void
1155 752
    {
1156 2
        if ($cellStyleIndex > count($this->cellXfCollection) - 1) {
1157 1
            throw new Exception('CellXf index is out of bounds.');
1158 1
        }
1159 1
1160
        // first remove the cellXf
1161 1
        array_splice($this->cellXfCollection, $cellStyleIndex, 1);
1162 1
1163
        // then update cellXf indexes for cells
1164 1
        foreach ($this->workSheetCollection as $worksheet) {
1165
            foreach ($worksheet->getCoordinates(false) as $coordinate) {
1166
                $cell = $worksheet->getCell($coordinate);
1167
                $xfIndex = $cell->getXfIndex();
1168
                if ($xfIndex > $cellStyleIndex) {
1169
                    // decrease xf index by 1
1170
                    $cell->setXfIndex($xfIndex - 1);
1171
                } elseif ($xfIndex == $cellStyleIndex) {
1172
                    // set to default xf index 0
1173 10000
                    $cell->setXfIndex(0);
1174
                }
1175 10000
            }
1176
        }
1177
    }
1178
1179
    /**
1180
     * Get the cellXf supervisor.
1181
     */
1182
    public function getCellXfSupervisor(): Style
1183 1
    {
1184
        return $this->cellXfSupervisor;
1185 1
    }
1186
1187
    /**
1188
     * Get the workbook collection of cellStyleXfs.
1189
     *
1190
     * @return Style[]
1191
     */
1192
    public function getCellStyleXfCollection(): array
1193 1
    {
1194
        return $this->cellStyleXfCollection;
1195 1
    }
1196
1197
    /**
1198
     * Get cellStyleXf by index.
1199
     *
1200
     * @param int $cellStyleIndex Index to cellXf
1201
     */
1202
    public function getCellStyleXfByIndex(int $cellStyleIndex): Style
1203 1
    {
1204
        return $this->cellStyleXfCollection[$cellStyleIndex];
1205 1
    }
1206 1
1207 1
    /**
1208
     * Get cellStyleXf by hash code.
1209
     *
1210
     * @return false|Style
1211 1
     */
1212
    public function getCellStyleXfByHashCode(string $hashcode): bool|Style
1213
    {
1214
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1215
            if ($cellStyleXf->getHashCode() === $hashcode) {
1216
                return $cellStyleXf;
1217 10374
            }
1218
        }
1219 10374
1220 10374
        return false;
1221
    }
1222
1223
    /**
1224
     * Add a cellStyleXf to the workbook.
1225
     */
1226
    public function addCellStyleXf(Style $style): void
1227
    {
1228 750
        $this->cellStyleXfCollection[] = $style;
1229
        $style->setIndex(count($this->cellStyleXfCollection) - 1);
1230 750
    }
1231 1
1232
    /**
1233 749
     * Remove cellStyleXf by index.
1234
     *
1235
     * @param int $cellStyleIndex Index to cellXf
1236
     */
1237
    public function removeCellStyleXfByIndex(int $cellStyleIndex): void
1238
    {
1239
        if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) {
1240 968
            throw new Exception('CellStyleXf index is out of bounds.');
1241
        }
1242
        array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1);
1243 968
    }
1244 968
1245 968
    /**
1246
     * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
1247
     * and columns in the workbook.
1248 968
     */
1249
    public function garbageCollect(): void
1250 968
    {
1251 941
        // how many references are there to each cellXf ?
1252 941
        $countReferencesCellXf = [];
1253
        foreach ($this->cellXfCollection as $index => $cellXf) {
1254
            $countReferencesCellXf[$index] = 0;
1255
        }
1256 968
1257 78
        foreach ($this->getWorksheetIterator() as $sheet) {
1258 11
            // from cells
1259
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1260
                $cell = $sheet->getCell($coordinate);
1261
                ++$countReferencesCellXf[$cell->getXfIndex()];
1262
            }
1263 968
1264 128
            // from row dimensions
1265
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1266
                if ($rowDimension->getXfIndex() !== null) {
1267
                    ++$countReferencesCellXf[$rowDimension->getXfIndex()];
1268
                }
1269
            }
1270 968
1271 968
            // from column dimensions
1272 968
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1273 968
                ++$countReferencesCellXf[$columnDimension->getXfIndex()];
1274 968
            }
1275
        }
1276 31
1277
        // remove cellXfs without references and create mapping so we can update xfIndex
1278 968
        // for all cells and columns
1279
        $countNeededCellXfs = 0;
1280 968
        $map = [];
1281
        foreach ($this->cellXfCollection as $index => $cellXf) {
1282
            if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
1283 968
                ++$countNeededCellXfs;
1284 968
            } else {
1285
                unset($this->cellXfCollection[$index]);
1286
            }
1287
            $map[$index] = $countNeededCellXfs - 1;
1288 968
        }
1289
        $this->cellXfCollection = array_values($this->cellXfCollection);
1290
1291
        // update the index for all cellXfs
1292
        foreach ($this->cellXfCollection as $i => $cellXf) {
1293 968
            $cellXf->setIndex($i);
1294
        }
1295 968
1296 941
        // make sure there is always at least one cellXf (there should be)
1297 941
        if (empty($this->cellXfCollection)) {
1298
            $this->cellXfCollection[] = new Style();
1299
        }
1300
1301 968
        // update the xfIndex for all cells, row dimensions, column dimensions
1302 78
        foreach ($this->getWorksheetIterator() as $sheet) {
1303 11
            // for all cells
1304
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1305
                $cell = $sheet->getCell($coordinate);
1306
                $cell->setXfIndex($map[$cell->getXfIndex()]);
1307
            }
1308 968
1309 128
            // for all row dimensions
1310
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1311
                if ($rowDimension->getXfIndex() !== null) {
1312
                    $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]);
1313 968
                }
1314
            }
1315
1316
            // for all column dimensions
1317
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1318
                $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]);
1319
            }
1320
1321
            // also do garbage collection for all the sheets
1322
            $sheet->garbageCollect();
1323
        }
1324
    }
1325
1326
    /**
1327
     * Return the unique ID value assigned to this spreadsheet workbook.
1328
     */
1329
    public function getID(): string
1330 364
    {
1331
        return $this->uniqueID;
1332 364
    }
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
    public function getShowHorizontalScroll(): bool
1340 248
    {
1341
        return $this->showHorizontalScroll;
1342 248
    }
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
    public function setShowHorizontalScroll(bool $showHorizontalScroll): void
1350 364
    {
1351
        $this->showHorizontalScroll = (bool) $showHorizontalScroll;
1352 364
    }
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
    public function getShowVerticalScroll(): bool
1360 248
    {
1361
        return $this->showVerticalScroll;
1362 248
    }
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
    public function setShowVerticalScroll(bool $showVerticalScroll): void
1370 364
    {
1371
        $this->showVerticalScroll = (bool) $showVerticalScroll;
1372 364
    }
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
    public function getShowSheetTabs(): bool
1380 248
    {
1381
        return $this->showSheetTabs;
1382 248
    }
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
    public function setShowSheetTabs(bool $showSheetTabs): void
1390 364
    {
1391
        $this->showSheetTabs = (bool) $showSheetTabs;
1392 364
    }
1393
1394
    /**
1395
     * Return whether the workbook window is minimized.
1396
     *
1397
     * @return bool true if workbook window is minimized
1398
     */
1399
    public function getMinimized(): bool
1400 242
    {
1401
        return $this->minimized;
1402 242
    }
1403
1404
    /**
1405
     * Set whether the workbook window is minimized.
1406
     *
1407
     * @param bool $minimized true if workbook window is minimized
1408
     */
1409
    public function setMinimized(bool $minimized): void
1410
    {
1411 364
        $this->minimized = (bool) $minimized;
1412
    }
1413 364
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
    public function getAutoFilterDateGrouping(): bool
1421
    {
1422 242
        return $this->autoFilterDateGrouping;
1423
    }
1424 242
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
    public function setAutoFilterDateGrouping(bool $autoFilterDateGrouping): void
1432 364
    {
1433
        $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping;
1434 364
    }
1435
1436
    /**
1437
     * Return the first sheet in the book view.
1438
     *
1439
     * @return int First sheet in book view
1440
     */
1441
    public function getFirstSheetIndex(): int
1442 250
    {
1443
        return $this->firstSheetIndex;
1444 250
    }
1445 249
1446
    /**
1447 1
     * Set the first sheet in the book view.
1448
     *
1449
     * @param int $firstSheetIndex First sheet in book view
1450
     */
1451
    public function setFirstSheetIndex(int $firstSheetIndex): void
1452
    {
1453
        if ($firstSheetIndex >= 0) {
1454
            $this->firstSheetIndex = (int) $firstSheetIndex;
1455
        } else {
1456
            throw new Exception('First sheet index must be a positive integer.');
1457
        }
1458
    }
1459 365
1460
    /**
1461 365
     * 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
    public function getVisibility(): string
1469
    {
1470
        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 243
     *  - 'hidden' (self::VISIBILITY_HIDDEN):
1480
     *       Workbook window is hidden, but can be shown by the user
1481 243
     *       via the user interface
1482 1
     *  - 'veryHidden' (self::VISIBILITY_VERY_HIDDEN):
1483
     *       Workbook window is hidden and cannot be shown in the
1484
     *       user interface.
1485 243
     *
1486 243
     * @param null|string $visibility visibility status of the workbook
1487
     */
1488 1
    public function setVisibility(?string $visibility): void
1489
    {
1490
        if ($visibility === null) {
1491
            $visibility = self::VISIBILITY_VISIBLE;
1492
        }
1493
1494
        if (in_array($visibility, self::WORKBOOK_VIEW_VISIBILITY_VALUES)) {
1495
            $this->visibility = $visibility;
1496
        } else {
1497
            throw new Exception('Invalid visibility value.');
1498 364
        }
1499
    }
1500 364
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
    public function getTabRatio(): int
1508
    {
1509 252
        return $this->tabRatio;
1510
    }
1511 252
1512 251
    /**
1513
     * Set the ratio between the workbook tabs bar and the horizontal scroll bar
1514 1
     * 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 2
    public function setTabRatio(int $tabRatio): void
1519
    {
1520 2
        if ($tabRatio >= 0 && $tabRatio <= 1000) {
1521 2
            $this->tabRatio = (int) $tabRatio;
1522 2
        } else {
1523 2
            throw new Exception('Tab ratio must be between 0 and 1000.');
1524 1
        }
1525
    }
1526 2
1527
    public function reevaluateAutoFilters(bool $resetToMax): void
1528
    {
1529
        foreach ($this->workSheetCollection as $sheet) {
1530
            $filter = $sheet->getAutoFilter();
1531
            if (!empty($filter->getRange())) {
1532
                if ($resetToMax) {
1533
                    $filter->setRangeToMaxRow();
1534 2
                }
1535
                $filter->showHideRows();
1536 2
            }
1537
        }
1538
    }
1539
1540
    /**
1541
     * @throws Exception
1542 1
     */
1543
    public function __serialize(): array
1544 1
    {
1545
        throw new Exception('Spreadsheet objects cannot be serialized');
1546
    }
1547 1
1548
    /**
1549 1
     * @throws Exception
1550 1
     */
1551 1
    public function jsonSerialize(): mixed
1552 1
    {
1553 1
        throw new Exception('Spreadsheet objects cannot be json encoded');
1554 1
    }
1555 1
1556 1
    public function resetThemeFonts(): void
1557
    {
1558
        $majorFontLatin = $this->theme->getMajorFontLatin();
1559 1
        $minorFontLatin = $this->theme->getMinorFontLatin();
1560 1
        foreach ($this->cellXfCollection as $cellStyleXf) {
1561 1
            $scheme = $cellStyleXf->getFont()->getScheme();
1562
            if ($scheme === 'major') {
1563 1
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1564 1
            } elseif ($scheme === 'minor') {
1565
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1566
            }
1567
        }
1568
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1569 36
            $scheme = $cellStyleXf->getFont()->getScheme();
1570
            if ($scheme === 'major') {
1571 36
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1572 36
            } elseif ($scheme === 'minor') {
1573 36
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1574 36
            }
1575 5
        }
1576
    }
1577
1578
    public function getTableByName(string $tableName): ?Table
1579 36
    {
1580
        $table = null;
1581
        foreach ($this->workSheetCollection as $sheet) {
1582
            $table = $sheet->getTableByName($tableName);
1583
            if ($table !== null) {
1584
                break;
1585 745
            }
1586
        }
1587 745
1588 745
        return $table;
1589
    }
1590 745
1591
    /**
1592
     * @return bool Success or failure
1593
     */
1594
    public function setExcelCalendar(int $baseYear): bool
1595
    {
1596
        if (($baseYear === Date::CALENDAR_WINDOWS_1900) || ($baseYear === Date::CALENDAR_MAC_1904)) {
1597
            $this->excelCalendar = $baseYear;
1598
1599 8350
            return true;
1600
        }
1601 8350
1602
        return false;
1603
    }
1604 2
1605
    /**
1606 2
     * @return int Excel base date (1900 or 1904)
1607
     */
1608
    public function getExcelCalendar(): int
1609 3
    {
1610
        return $this->excelCalendar;
1611 3
    }
1612
1613
    public function deleteLegacyDrawing(Worksheet $worksheet): void
1614 9545
    {
1615
        unset($this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing']);
1616 9545
    }
1617
1618
    public function getLegacyDrawing(Worksheet $worksheet): ?string
1619 1493
    {
1620
        return $this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'] ?? null;
1621 1493
    }
1622
1623 1493
    public function getValueBinder(): ?IValueBinder
1624
    {
1625
        return $this->valueBinder;
1626
    }
1627
1628
    public function setValueBinder(?IValueBinder $valueBinder): self
1629
    {
1630
        $this->valueBinder = $valueBinder;
1631
1632
        return $this;
1633
    }
1634
}
1635