Passed
Push — master ( 653645...08f2f1 )
by
unknown
16:09 queued 04:49
created

Spreadsheet::getDefinedName()   B

Complexity

Conditions 10
Paths 12

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 10

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 39
ccs 22
cts 22
cp 1
rs 7.6666
c 0
b 0
f 0
cc 10
nc 12
nop 2
crap 10

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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