Passed
Pull Request — master (#4370)
by Owen
14:37
created

Spreadsheet::getID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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