Failed Conditions
Pull Request — master (#4501)
by Owen
18:19 queued 10:13
created

Spreadsheet::getFontCharsets()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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