Spreadsheet::getValueBinder()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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