Passed
Pull Request — master (#4501)
by Owen
11:46
created

Spreadsheet::getFontCharset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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