Passed
Pull Request — master (#4317)
by Owen
20:45
created

Spreadsheet::getCellXfByIndexOrNull()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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