Failed Conditions
Pull Request — master (#3528)
by Owen
22:55 queued 12:36
created

Worksheet::refreshRowDimensions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4
5
use ArrayObject;
6
use Generator;
7
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
8
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
9
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
10
use PhpOffice\PhpSpreadsheet\Cell\Cell;
11
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
12
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
13
use PhpOffice\PhpSpreadsheet\Cell\DataType;
14
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
15
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
16
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
17
use PhpOffice\PhpSpreadsheet\Chart\Chart;
18
use PhpOffice\PhpSpreadsheet\Collection\Cells;
19
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
20
use PhpOffice\PhpSpreadsheet\Comment;
21
use PhpOffice\PhpSpreadsheet\DefinedName;
22
use PhpOffice\PhpSpreadsheet\Exception;
23
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
24
use PhpOffice\PhpSpreadsheet\RichText\RichText;
25
use PhpOffice\PhpSpreadsheet\Shared;
26
use PhpOffice\PhpSpreadsheet\Spreadsheet;
27
use PhpOffice\PhpSpreadsheet\Style\Alignment;
28
use PhpOffice\PhpSpreadsheet\Style\Color;
29
use PhpOffice\PhpSpreadsheet\Style\Conditional;
30
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
31
use PhpOffice\PhpSpreadsheet\Style\Protection as StyleProtection;
32
use PhpOffice\PhpSpreadsheet\Style\Style;
33
34
class Worksheet
35
{
36
    // Break types
37
    public const BREAK_NONE = 0;
38
    public const BREAK_ROW = 1;
39
    public const BREAK_COLUMN = 2;
40
    // Maximum column for row break
41
    public const BREAK_ROW_MAX_COLUMN = 16383;
42
43
    // Sheet state
44
    public const SHEETSTATE_VISIBLE = 'visible';
45
    public const SHEETSTATE_HIDDEN = 'hidden';
46
    public const SHEETSTATE_VERYHIDDEN = 'veryHidden';
47
48
    public const MERGE_CELL_CONTENT_EMPTY = 'empty';
49
    public const MERGE_CELL_CONTENT_HIDE = 'hide';
50
    public const MERGE_CELL_CONTENT_MERGE = 'merge';
51
52
    public const FUNCTION_LIKE_GROUPBY = '/\\b(groupby|_xleta)\\b/i'; // weird new syntax
53
54
    protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui';
55
56
    /**
57
     * Maximum 31 characters allowed for sheet title.
58
     *
59
     * @var int
60
     */
61
    const SHEET_TITLE_MAXIMUM_LENGTH = 31;
62
63
    /**
64
     * Invalid characters in sheet title.
65
     */
66
    private static array $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']'];
67
68
    /**
69
     * Parent spreadsheet.
70
     */
71
    private ?Spreadsheet $parent = null;
72
73
    /**
74
     * Collection of cells.
75
     */
76
    private Cells $cellCollection;
77
78
    private bool $cellCollectionInitialized = true;
79
80
    /**
81
     * Collection of row dimensions.
82
     *
83
     * @var RowDimension[]
84
     */
85
    private array $rowDimensions = [];
86
87
    /**
88
     * Default row dimension.
89
     */
90
    private RowDimension $defaultRowDimension;
91
92
    /**
93
     * Collection of column dimensions.
94
     *
95
     * @var ColumnDimension[]
96
     */
97
    private array $columnDimensions = [];
98
99
    /**
100
     * Default column dimension.
101
     */
102
    private ColumnDimension $defaultColumnDimension;
103
104
    /**
105
     * Collection of drawings.
106
     *
107
     * @var ArrayObject<int, BaseDrawing>
108
     */
109
    private ArrayObject $drawingCollection;
110
111
    /**
112
     * Collection of Chart objects.
113
     *
114
     * @var ArrayObject<int, Chart>
115
     */
116
    private ArrayObject $chartCollection;
117
118
    /**
119
     * Collection of Table objects.
120
     *
121
     * @var ArrayObject<int, Table>
122
     */
123
    private ArrayObject $tableCollection;
124
125
    /**
126
     * Worksheet title.
127
     */
128
    private string $title = '';
129
130
    /**
131
     * Sheet state.
132
     */
133
    private string $sheetState;
134
135
    /**
136
     * Page setup.
137
     */
138
    private PageSetup $pageSetup;
139
140
    /**
141
     * Page margins.
142
     */
143
    private PageMargins $pageMargins;
144
145
    /**
146
     * Page header/footer.
147
     */
148
    private HeaderFooter $headerFooter;
149
150
    /**
151
     * Sheet view.
152
     */
153
    private SheetView $sheetView;
154
155
    /**
156
     * Protection.
157
     */
158
    private Protection $protection;
159
160
    /**
161
     * Collection of styles.
162
     *
163
     * @var Style[]
164
     */
165
    private array $styles = [];
166
167
    /**
168
     * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
169
     */
170
    private array $conditionalStylesCollection = [];
171
172
    /**
173
     * Collection of row breaks.
174
     *
175
     * @var PageBreak[]
176
     */
177
    private array $rowBreaks = [];
178
179
    /**
180
     * Collection of column breaks.
181
     *
182
     * @var PageBreak[]
183
     */
184
    private array $columnBreaks = [];
185
186
    /**
187
     * Collection of merged cell ranges.
188
     *
189
     * @var string[]
190
     */
191
    private array $mergeCells = [];
192
193
    /**
194
     * Collection of protected cell ranges.
195
     *
196
     * @var ProtectedRange[]
197
     */
198
    private array $protectedCells = [];
199
200
    /**
201
     * Autofilter Range and selection.
202
     */
203
    private AutoFilter $autoFilter;
204
205
    /**
206
     * Freeze pane.
207
     */
208
    private ?string $freezePane = null;
209
210
    /**
211
     * Default position of the right bottom pane.
212
     */
213
    private ?string $topLeftCell = null;
214
215
    private string $paneTopLeftCell = '';
216
217
    private string $activePane = '';
218
219
    private int $xSplit = 0;
220
221
    private int $ySplit = 0;
222
223
    private string $paneState = '';
224
225
    /**
226
     * Properties of the 4 panes.
227
     *
228
     * @var (null|Pane)[]
229
     */
230
    private array $panes = [
231
        'bottomRight' => null,
232
        'bottomLeft' => null,
233
        'topRight' => null,
234
        'topLeft' => null,
235
    ];
236
237
    /**
238
     * Show gridlines?
239
     */
240
    private bool $showGridlines = true;
241
242
    /**
243
     * Print gridlines?
244
     */
245
    private bool $printGridlines = false;
246
247
    /**
248
     * Show row and column headers?
249
     */
250
    private bool $showRowColHeaders = true;
251
252
    /**
253
     * Show summary below? (Row/Column outline).
254
     */
255
    private bool $showSummaryBelow = true;
256
257
    /**
258
     * Show summary right? (Row/Column outline).
259
     */
260
    private bool $showSummaryRight = true;
261
262
    /**
263
     * Collection of comments.
264
     *
265
     * @var Comment[]
266
     */
267
    private array $comments = [];
268
269
    /**
270
     * Active cell. (Only one!).
271
     */
272
    private string $activeCell = 'A1';
273
274
    /**
275
     * Selected cells.
276
     */
277
    private string $selectedCells = 'A1';
278
279
    /**
280
     * Cached highest column.
281
     */
282
    private int $cachedHighestColumn = 1;
283
284
    /**
285
     * Cached highest row.
286
     */
287
    private int $cachedHighestRow = 1;
288
289
    /**
290
     * Right-to-left?
291
     */
292
    private bool $rightToLeft = false;
293
294
    /**
295
     * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
296
     */
297
    private array $hyperlinkCollection = [];
298
299
    /**
300
     * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
301
     */
302
    private array $dataValidationCollection = [];
303
304
    /**
305
     * Tab color.
306
     */
307
    private ?Color $tabColor = null;
308
309
    /**
310
     * Hash.
311
     */
312
    private int $hash;
313
314
    /**
315
     * CodeName.
316
     */
317
    private ?string $codeName = null;
318
319
    /**
320
     * Create a new worksheet.
321
     */
322 10417
    public function __construct(?Spreadsheet $parent = null, string $title = 'Worksheet')
323
    {
324
        // Set parent and title
325 10417
        $this->parent = $parent;
326 10417
        $this->hash = spl_object_id($this);
327 10417
        $this->setTitle($title, false);
328
        // setTitle can change $pTitle
329 10417
        $this->setCodeName($this->getTitle());
330 10417
        $this->setSheetState(self::SHEETSTATE_VISIBLE);
331
332 10417
        $this->cellCollection = CellsFactory::getInstance($this);
333
        // Set page setup
334 10417
        $this->pageSetup = new PageSetup();
335
        // Set page margins
336 10417
        $this->pageMargins = new PageMargins();
337
        // Set page header/footer
338 10417
        $this->headerFooter = new HeaderFooter();
339
        // Set sheet view
340 10417
        $this->sheetView = new SheetView();
341
        // Drawing collection
342 10417
        $this->drawingCollection = new ArrayObject();
343
        // Chart collection
344 10417
        $this->chartCollection = new ArrayObject();
345
        // Protection
346 10417
        $this->protection = new Protection();
347
        // Default row dimension
348 10417
        $this->defaultRowDimension = new RowDimension(null);
349
        // Default column dimension
350 10417
        $this->defaultColumnDimension = new ColumnDimension(null);
351
        // AutoFilter
352 10417
        $this->autoFilter = new AutoFilter('', $this);
353
        // Table collection
354 10417
        $this->tableCollection = new ArrayObject();
355
    }
356
357
    /**
358
     * Disconnect all cells from this Worksheet object,
359
     * typically so that the worksheet object can be unset.
360
     */
361 9034
    public function disconnectCells(): void
362
    {
363 9034
        if ($this->cellCollectionInitialized) {
364 9033
            $this->cellCollection->unsetWorksheetCells();
365 9033
            unset($this->cellCollection);
366 9033
            $this->cellCollectionInitialized = false;
367
        }
368
        //    detach ourself from the workbook, so that it can then delete this worksheet successfully
369 9034
        $this->parent = null;
370
    }
371
372
    /**
373
     * Code to execute when this worksheet is unset().
374
     */
375 119
    public function __destruct()
376
    {
377 119
        Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
378
379 119
        $this->disconnectCells();
380 119
        unset($this->rowDimensions, $this->columnDimensions, $this->tableCollection, $this->drawingCollection, $this->chartCollection, $this->autoFilter);
381
    }
382
383 1
    public function __wakeup(): void
384
    {
385 1
        $this->hash = spl_object_id($this);
386 1
        $this->parent = null;
387
    }
388
389
    /**
390
     * Return the cell collection.
391
     */
392 10097
    public function getCellCollection(): Cells
393
    {
394 10097
        return $this->cellCollection;
395
    }
396
397
    /**
398
     * Get array of invalid characters for sheet title.
399
     */
400 1
    public static function getInvalidCharacters(): array
401
    {
402 1
        return self::$invalidCharacters;
403
    }
404
405
    /**
406
     * Check sheet code name for valid Excel syntax.
407
     *
408
     * @param string $sheetCodeName The string to check
409
     *
410
     * @return string The valid string
411
     */
412 10417
    private static function checkSheetCodeName(string $sheetCodeName): string
413
    {
414 10417
        $charCount = Shared\StringHelper::countCharacters($sheetCodeName);
415 10417
        if ($charCount == 0) {
416 1
            throw new Exception('Sheet code name cannot be empty.');
417
        }
418
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ] and  first and last characters cannot be a "'"
419
        if (
420 10417
            (str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName)
421 10417
            || (Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'')
422 10417
            || (Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'')
423
        ) {
424 1
            throw new Exception('Invalid character found in sheet code name');
425
        }
426
427
        // Enforce maximum characters allowed for sheet title
428 10417
        if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
429 1
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
430
        }
431
432 10417
        return $sheetCodeName;
433
    }
434
435
    /**
436
     * Check sheet title for valid Excel syntax.
437
     *
438
     * @param string $sheetTitle The string to check
439
     *
440
     * @return string The valid string
441
     */
442 10417
    private static function checkSheetTitle(string $sheetTitle): string
443
    {
444
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ]
445 10417
        if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) {
446 2
            throw new Exception('Invalid character found in sheet title');
447
        }
448
449
        // Enforce maximum characters allowed for sheet title
450 10417
        if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
451 3
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
452
        }
453
454 10417
        return $sheetTitle;
455
    }
456
457
    /**
458
     * Get a sorted list of all cell coordinates currently held in the collection by row and column.
459
     *
460
     * @param bool $sorted Also sort the cell collection?
461
     *
462
     * @return string[]
463
     */
464 1366
    public function getCoordinates(bool $sorted = true): array
465
    {
466 1366
        if ($this->cellCollectionInitialized === false) {
467 1
            return [];
468
        }
469
470 1365
        if ($sorted) {
471 484
            return $this->cellCollection->getSortedCoordinates();
472
        }
473
474 1275
        return $this->cellCollection->getCoordinates();
475
    }
476
477
    /**
478
     * Get collection of row dimensions.
479
     *
480
     * @return RowDimension[]
481
     */
482 1092
    public function getRowDimensions(): array
483
    {
484 1092
        return $this->rowDimensions;
485
    }
486
487
    /**
488
     * Get default row dimension.
489
     */
490 1042
    public function getDefaultRowDimension(): RowDimension
491
    {
492 1042
        return $this->defaultRowDimension;
493
    }
494
495
    /**
496
     * Get collection of column dimensions.
497
     *
498
     * @return ColumnDimension[]
499
     */
500 1098
    public function getColumnDimensions(): array
501
    {
502
        /** @var callable $callable */
503 1098
        $callable = [self::class, 'columnDimensionCompare'];
504 1098
        uasort($this->columnDimensions, $callable);
505
506 1098
        return $this->columnDimensions;
507
    }
508
509 80
    private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int
510
    {
511 80
        return $a->getColumnNumeric() - $b->getColumnNumeric();
512
    }
513
514
    /**
515
     * Get default column dimension.
516
     */
517 508
    public function getDefaultColumnDimension(): ColumnDimension
518
    {
519 508
        return $this->defaultColumnDimension;
520
    }
521
522
    /**
523
     * Get collection of drawings.
524
     *
525
     * @return ArrayObject<int, BaseDrawing>
526
     */
527 1072
    public function getDrawingCollection(): ArrayObject
528
    {
529 1072
        return $this->drawingCollection;
530
    }
531
532
    /**
533
     * Get collection of charts.
534
     *
535
     * @return ArrayObject<int, Chart>
536
     */
537 100
    public function getChartCollection(): ArrayObject
538
    {
539 100
        return $this->chartCollection;
540
    }
541
542 105
    public function addChart(Chart $chart): Chart
543
    {
544 105
        $chart->setWorksheet($this);
545 105
        $this->chartCollection[] = $chart;
546
547 105
        return $chart;
548
    }
549
550
    /**
551
     * Return the count of charts on this worksheet.
552
     *
553
     * @return int The number of charts
554
     */
555 83
    public function getChartCount(): int
556
    {
557 83
        return count($this->chartCollection);
558
    }
559
560
    /**
561
     * Get a chart by its index position.
562
     *
563
     * @param ?string $index Chart index position
564
     *
565
     * @return Chart|false
566
     */
567 77
    public function getChartByIndex(?string $index)
568
    {
569 77
        $chartCount = count($this->chartCollection);
570 77
        if ($chartCount == 0) {
571
            return false;
572
        }
573 77
        if ($index === null) {
574
            $index = --$chartCount;
575
        }
576 77
        if (!isset($this->chartCollection[$index])) {
577
            return false;
578
        }
579
580 77
        return $this->chartCollection[$index];
581
    }
582
583
    /**
584
     * Return an array of the names of charts on this worksheet.
585
     *
586
     * @return string[] The names of charts
587
     */
588 5
    public function getChartNames(): array
589
    {
590 5
        $chartNames = [];
591 5
        foreach ($this->chartCollection as $chart) {
592 5
            $chartNames[] = $chart->getName();
593
        }
594
595 5
        return $chartNames;
596
    }
597
598
    /**
599
     * Get a chart by name.
600
     *
601
     * @param string $chartName Chart name
602
     *
603
     * @return Chart|false
604
     */
605 6
    public function getChartByName(string $chartName)
606
    {
607 6
        foreach ($this->chartCollection as $index => $chart) {
608 6
            if ($chart->getName() == $chartName) {
609 6
                return $chart;
610
            }
611
        }
612
613 1
        return false;
614
    }
615
616 6
    public function getChartByNameOrThrow(string $chartName): Chart
617
    {
618 6
        $chart = $this->getChartByName($chartName);
619 6
        if ($chart !== false) {
620 6
            return $chart;
621
        }
622
623 1
        throw new Exception("Sheet does not have a chart named $chartName.");
624
    }
625
626
    /**
627
     * Refresh column dimensions.
628
     *
629
     * @return $this
630
     */
631 25
    public function refreshColumnDimensions(): static
632
    {
633 25
        $newColumnDimensions = [];
634 25
        foreach ($this->getColumnDimensions() as $objColumnDimension) {
635 25
            $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
636
        }
637
638 25
        $this->columnDimensions = $newColumnDimensions;
639
640 25
        return $this;
641
    }
642
643
    /**
644
     * Refresh row dimensions.
645
     *
646
     * @return $this
647
     */
648 7
    public function refreshRowDimensions(): static
649
    {
650 7
        $newRowDimensions = [];
651 7
        foreach ($this->getRowDimensions() as $objRowDimension) {
652 7
            $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
653
        }
654
655 7
        $this->rowDimensions = $newRowDimensions;
656
657 7
        return $this;
658
    }
659
660
    /**
661
     * Calculate worksheet dimension.
662
     *
663
     * @return string String containing the dimension of this worksheet
664
     */
665 422
    public function calculateWorksheetDimension(): string
666
    {
667
        // Return
668 422
        return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
669
    }
670
671
    /**
672
     * Calculate worksheet data dimension.
673
     *
674
     * @return string String containing the dimension of this worksheet that actually contain data
675
     */
676 532
    public function calculateWorksheetDataDimension(): string
677
    {
678
        // Return
679 532
        return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
680
    }
681
682
    /**
683
     * Calculate widths for auto-size columns.
684
     *
685
     * @return $this
686
     */
687 735
    public function calculateColumnWidths(): static
688
    {
689 735
        $activeSheet = $this->getParent()?->getActiveSheetIndex();
690 735
        $selectedCells = $this->selectedCells;
691
        // initialize $autoSizes array
692 735
        $autoSizes = [];
693 735
        foreach ($this->getColumnDimensions() as $colDimension) {
694 134
            if ($colDimension->getAutoSize()) {
695 58
                $autoSizes[$colDimension->getColumnIndex()] = -1;
696
            }
697
        }
698
699
        // There is only something to do if there are some auto-size columns
700 735
        if (!empty($autoSizes)) {
701 58
            $holdActivePane = $this->activePane;
702
            // build list of cells references that participate in a merge
703 58
            $isMergeCell = [];
704 58
            foreach ($this->getMergeCells() as $cells) {
705 16
                foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
706 16
                    $isMergeCell[$cellReference] = true;
707
                }
708
            }
709
710 58
            $autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges();
711
712
            // loop through all cells in the worksheet
713 58
            foreach ($this->getCoordinates(false) as $coordinate) {
714 58
                $cell = $this->getCellOrNull($coordinate);
715
716 58
                if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
717
                    //Determine if cell is in merge range
718 58
                    $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
719
720
                    //By default merged cells should be ignored
721 58
                    $isMergedButProceed = false;
722
723
                    //The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide)
724 58
                    if ($isMerged && $cell->isMergeRangeValueCell()) {
725
                        $range = (string) $cell->getMergeRange();
726
                        $rangeBoundaries = Coordinate::rangeDimension($range);
727
                        if ($rangeBoundaries[0] === 1) {
728
                            $isMergedButProceed = true;
729
                        }
730
                    }
731
732
                    // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range
733 58
                    if (!$isMerged || $isMergedButProceed) {
734
                        // Determine if we need to make an adjustment for the first row in an AutoFilter range that
735
                        //    has a column filter dropdown
736 58
                        $filterAdjustment = false;
737 58
                        if (!empty($autoFilterIndentRanges)) {
738 4
                            foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) {
739 4
                                if ($cell->isInRange($autoFilterFirstRowRange)) {
740 4
                                    $filterAdjustment = true;
741
742 4
                                    break;
743
                                }
744
                            }
745
                        }
746
747 58
                        $indentAdjustment = $cell->getStyle()->getAlignment()->getIndent();
748 58
                        $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER);
749
750
                        // Calculated value
751
                        // To formatted string
752 58
                        $cellValue = NumberFormat::toFormattedString(
753 58
                            $cell->getCalculatedValueString(),
754 58
                            (string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
755 58
                                ->getNumberFormat()->getFormatCode(true)
756 58
                        );
757
758 58
                        if ($cellValue !== null && $cellValue !== '') {
759 58
                            $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
760 58
                                $autoSizes[$this->cellCollection->getCurrentColumn()],
761 58
                                round(
762 58
                                    Shared\Font::calculateColumnWidth(
763 58
                                        $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(),
764 58
                                        $cellValue,
765 58
                                        (int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
766 58
                                            ->getAlignment()->getTextRotation(),
767 58
                                        $this->getParentOrThrow()->getDefaultStyle()->getFont(),
768 58
                                        $filterAdjustment,
769 58
                                        $indentAdjustment
770 58
                                    ),
771 58
                                    3
772 58
                                )
773 58
                            );
774
                        }
775
                    }
776
                }
777
            }
778
779
            // adjust column widths
780 58
            foreach ($autoSizes as $columnIndex => $width) {
781 58
                if ($width == -1) {
782
                    $width = $this->getDefaultColumnDimension()->getWidth();
783
                }
784 58
                $this->getColumnDimension($columnIndex)->setWidth($width);
785
            }
786 58
            $this->activePane = $holdActivePane;
787
        }
788 735
        if ($activeSheet !== null && $activeSheet >= 0) {
789 735
            $this->getParent()?->setActiveSheetIndex($activeSheet);
790
        }
791 735
        $this->setSelectedCells($selectedCells);
792
793 735
        return $this;
794
    }
795
796
    /**
797
     * Get parent or null.
798
     */
799 10100
    public function getParent(): ?Spreadsheet
800
    {
801 10100
        return $this->parent;
802
    }
803
804
    /**
805
     * Get parent, throw exception if null.
806
     */
807 10131
    public function getParentOrThrow(): Spreadsheet
808
    {
809 10131
        if ($this->parent !== null) {
810 10130
            return $this->parent;
811
        }
812
813 1
        throw new Exception('Sheet does not have a parent.');
814
    }
815
816
    /**
817
     * Re-bind parent.
818
     *
819
     * @return $this
820
     */
821 54
    public function rebindParent(Spreadsheet $parent): static
822
    {
823 54
        if ($this->parent !== null) {
824 4
            $definedNames = $this->parent->getDefinedNames();
825 4
            foreach ($definedNames as $definedName) {
826
                $parent->addDefinedName($definedName);
827
            }
828
829 4
            $this->parent->removeSheetByIndex(
830 4
                $this->parent->getIndex($this)
831 4
            );
832
        }
833 54
        $this->parent = $parent;
834
835 54
        return $this;
836
    }
837
838
    /**
839
     * Get title.
840
     */
841 10417
    public function getTitle(): string
842
    {
843 10417
        return $this->title;
844
    }
845
846
    /**
847
     * Set title.
848
     *
849
     * @param string $title String containing the dimension of this worksheet
850
     * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
851
     *            be updated to reflect the new sheet name.
852
     *          This should be left as the default true, unless you are
853
     *          certain that no formula cells on any worksheet contain
854
     *          references to this worksheet
855
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
856
     *                       at parse time (by Readers), where titles can be assumed to be valid.
857
     *
858
     * @return $this
859
     */
860 10417
    public function setTitle(string $title, bool $updateFormulaCellReferences = true, bool $validate = true): static
861
    {
862
        // Is this a 'rename' or not?
863 10417
        if ($this->getTitle() == $title) {
864 262
            return $this;
865
        }
866
867
        // Old title
868 10417
        $oldTitle = $this->getTitle();
869
870 10417
        if ($validate) {
871
            // Syntax check
872 10417
            self::checkSheetTitle($title);
873
874 10417
            if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
875
                // Is there already such sheet name?
876 791
                if ($this->parent->sheetNameExists($title)) {
877
                    // Use name, but append with lowest possible integer
878
879 2
                    if (Shared\StringHelper::countCharacters($title) > 29) {
880
                        $title = Shared\StringHelper::substring($title, 0, 29);
881
                    }
882 2
                    $i = 1;
883 2
                    while ($this->parent->sheetNameExists($title . ' ' . $i)) {
884 1
                        ++$i;
885 1
                        if ($i == 10) {
886
                            if (Shared\StringHelper::countCharacters($title) > 28) {
887
                                $title = Shared\StringHelper::substring($title, 0, 28);
888
                            }
889 1
                        } elseif ($i == 100) {
890
                            if (Shared\StringHelper::countCharacters($title) > 27) {
891
                                $title = Shared\StringHelper::substring($title, 0, 27);
892
                            }
893
                        }
894
                    }
895
896 2
                    $title .= " $i";
897
                }
898
            }
899
        }
900
901
        // Set title
902 10417
        $this->title = $title;
903
904 10417
        if ($this->parent && $this->parent->getIndex($this, true) >= 0 && $this->parent->getCalculationEngine()) {
905
            // New title
906 1369
            $newTitle = $this->getTitle();
907 1369
            $this->parent->getCalculationEngine()
908 1369
                ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
909 1369
            if ($updateFormulaCellReferences) {
910 791
                ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle);
911
            }
912
        }
913
914 10417
        return $this;
915
    }
916
917
    /**
918
     * Get sheet state.
919
     *
920
     * @return string Sheet state (visible, hidden, veryHidden)
921
     */
922 464
    public function getSheetState(): string
923
    {
924 464
        return $this->sheetState;
925
    }
926
927
    /**
928
     * Set sheet state.
929
     *
930
     * @param string $value Sheet state (visible, hidden, veryHidden)
931
     *
932
     * @return $this
933
     */
934 10417
    public function setSheetState(string $value): static
935
    {
936 10417
        $this->sheetState = $value;
937
938 10417
        return $this;
939
    }
940
941
    /**
942
     * Get page setup.
943
     */
944 1477
    public function getPageSetup(): PageSetup
945
    {
946 1477
        return $this->pageSetup;
947
    }
948
949
    /**
950
     * Set page setup.
951
     *
952
     * @return $this
953
     */
954 1
    public function setPageSetup(PageSetup $pageSetup): static
955
    {
956 1
        $this->pageSetup = $pageSetup;
957
958 1
        return $this;
959
    }
960
961
    /**
962
     * Get page margins.
963
     */
964 1491
    public function getPageMargins(): PageMargins
965
    {
966 1491
        return $this->pageMargins;
967
    }
968
969
    /**
970
     * Set page margins.
971
     *
972
     * @return $this
973
     */
974 1
    public function setPageMargins(PageMargins $pageMargins): static
975
    {
976 1
        $this->pageMargins = $pageMargins;
977
978 1
        return $this;
979
    }
980
981
    /**
982
     * Get page header/footer.
983
     */
984 516
    public function getHeaderFooter(): HeaderFooter
985
    {
986 516
        return $this->headerFooter;
987
    }
988
989
    /**
990
     * Set page header/footer.
991
     *
992
     * @return $this
993
     */
994 1
    public function setHeaderFooter(HeaderFooter $headerFooter): static
995
    {
996 1
        $this->headerFooter = $headerFooter;
997
998 1
        return $this;
999
    }
1000
1001
    /**
1002
     * Get sheet view.
1003
     */
1004 542
    public function getSheetView(): SheetView
1005
    {
1006 542
        return $this->sheetView;
1007
    }
1008
1009
    /**
1010
     * Set sheet view.
1011
     *
1012
     * @return $this
1013
     */
1014 1
    public function setSheetView(SheetView $sheetView): static
1015
    {
1016 1
        $this->sheetView = $sheetView;
1017
1018 1
        return $this;
1019
    }
1020
1021
    /**
1022
     * Get Protection.
1023
     */
1024 567
    public function getProtection(): Protection
1025
    {
1026 567
        return $this->protection;
1027
    }
1028
1029
    /**
1030
     * Set Protection.
1031
     *
1032
     * @return $this
1033
     */
1034 1
    public function setProtection(Protection $protection): static
1035
    {
1036 1
        $this->protection = $protection;
1037
1038 1
        return $this;
1039
    }
1040
1041
    /**
1042
     * Get highest worksheet column.
1043
     *
1044
     * @param null|int|string $row Return the data highest column for the specified row,
1045
     *                                     or the highest column of any row if no row number is passed
1046
     *
1047
     * @return string Highest column name
1048
     */
1049 1393
    public function getHighestColumn($row = null): string
1050
    {
1051 1393
        if ($row === null) {
1052 1392
            return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
1053
        }
1054
1055 1
        return $this->getHighestDataColumn($row);
1056
    }
1057
1058
    /**
1059
     * Get highest worksheet column that contains data.
1060
     *
1061
     * @param null|int|string $row Return the highest data column for the specified row,
1062
     *                                     or the highest data column of any row if no row number is passed
1063
     *
1064
     * @return string Highest column name that contains data
1065
     */
1066 660
    public function getHighestDataColumn($row = null): string
1067
    {
1068 660
        return $this->cellCollection->getHighestColumn($row);
1069
    }
1070
1071
    /**
1072
     * Get highest worksheet row.
1073
     *
1074
     * @param null|string $column Return the highest data row for the specified column,
1075
     *                                     or the highest row of any column if no column letter is passed
1076
     *
1077
     * @return int Highest row number
1078
     */
1079 892
    public function getHighestRow(?string $column = null): int
1080
    {
1081 892
        if ($column === null) {
1082 891
            return $this->cachedHighestRow;
1083
        }
1084
1085 1
        return $this->getHighestDataRow($column);
1086
    }
1087
1088
    /**
1089
     * Get highest worksheet row that contains data.
1090
     *
1091
     * @param null|string $column Return the highest data row for the specified column,
1092
     *                                     or the highest data row of any column if no column letter is passed
1093
     *
1094
     * @return int Highest row number that contains data
1095
     */
1096 659
    public function getHighestDataRow(?string $column = null): int
1097
    {
1098 659
        return $this->cellCollection->getHighestRow($column);
1099
    }
1100
1101
    /**
1102
     * Get highest worksheet column and highest row that have cell records.
1103
     *
1104
     * @return array Highest column name and highest row number
1105
     */
1106 1
    public function getHighestRowAndColumn(): array
1107
    {
1108 1
        return $this->cellCollection->getHighestRowAndColumn();
1109
    }
1110
1111
    /**
1112
     * Set a cell value.
1113
     *
1114
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1115
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1116
     * @param mixed $value Value for the cell
1117
     * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
1118
     *
1119
     * @return $this
1120
     */
1121 4664
    public function setCellValue(CellAddress|string|array $coordinate, mixed $value, ?IValueBinder $binder = null): static
1122
    {
1123 4664
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1124 4664
        $this->getCell($cellAddress)->setValue($value, $binder);
1125
1126 4664
        return $this;
1127
    }
1128
1129
    /**
1130
     * Set a cell value.
1131
     *
1132
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1133
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1134
     * @param mixed $value Value of the cell
1135
     * @param string $dataType Explicit data type, see DataType::TYPE_*
1136
     *        Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
1137
     *             method, then it is your responsibility as an end-user developer to validate that the value and
1138
     *             the datatype match.
1139
     *       If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype
1140
     *          that you specify.
1141
     *
1142
     * @see DataType
1143
     *
1144
     * @return $this
1145
     */
1146 104
    public function setCellValueExplicit(CellAddress|string|array $coordinate, mixed $value, string $dataType): static
1147
    {
1148 104
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1149 104
        $this->getCell($cellAddress)->setValueExplicit($value, $dataType);
1150
1151 104
        return $this;
1152
    }
1153
1154
    /**
1155
     * Get cell at a specific coordinate.
1156
     *
1157
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1158
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1159
     *
1160
     * @return Cell Cell that was found or created
1161
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1162
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1163
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1164
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1165
     *              the active cell has changed.
1166
     */
1167 10057
    public function getCell(CellAddress|string|array $coordinate): Cell
1168
    {
1169 10057
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1170
1171
        // Shortcut for increased performance for the vast majority of simple cases
1172 10057
        if ($this->cellCollection->has($cellAddress)) {
1173
            /** @var Cell $cell */
1174 10024
            $cell = $this->cellCollection->get($cellAddress);
1175
1176 10024
            return $cell;
1177
        }
1178
1179
        /** @var Worksheet $sheet */
1180 10057
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
1181 10057
        $cell = $sheet->getCellCollection()->get($finalCoordinate);
1182
1183 10057
        return $cell ?? $sheet->createNewCell($finalCoordinate);
1184
    }
1185
1186
    /**
1187
     * Get the correct Worksheet and coordinate from a coordinate that may
1188
     * contains reference to another sheet or a named range.
1189
     *
1190
     * @return array{0: Worksheet, 1: string}
1191
     */
1192 10059
    private function getWorksheetAndCoordinate(string $coordinate): array
1193
    {
1194 10059
        $sheet = null;
1195 10059
        $finalCoordinate = null;
1196
1197
        // Worksheet reference?
1198 10059
        if (str_contains($coordinate, '!')) {
1199
            $worksheetReference = self::extractSheetTitle($coordinate, true);
1200
1201
            $sheet = $this->getParentOrThrow()->getSheetByName($worksheetReference[0]);
1202
            $finalCoordinate = strtoupper($worksheetReference[1]);
1203
1204
            if ($sheet === null) {
1205
                throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
1206
            }
1207
        } elseif (
1208 10059
            !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate)
1209 10059
            && preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate)
1210
        ) {
1211
            // Named range?
1212 15
            $namedRange = $this->validateNamedRange($coordinate, true);
1213 15
            if ($namedRange !== null) {
1214 10
                $sheet = $namedRange->getWorksheet();
1215 10
                if ($sheet === null) {
1216
                    throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
1217
                }
1218
1219
                /** @phpstan-ignore-next-line */
1220 10
                $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
1221 10
                $finalCoordinate = str_replace('$', '', $cellCoordinate);
1222
            }
1223
        }
1224
1225 10059
        if ($sheet === null || $finalCoordinate === null) {
1226 10059
            $sheet = $this;
1227 10059
            $finalCoordinate = strtoupper($coordinate);
1228
        }
1229
1230 10059
        if (Coordinate::coordinateIsRange($finalCoordinate)) {
1231 2
            throw new Exception('Cell coordinate string can not be a range of cells.');
1232 10059
        } elseif (str_contains($finalCoordinate, '$')) {
1233
            throw new Exception('Cell coordinate must not be absolute.');
1234
        }
1235
1236 10059
        return [$sheet, $finalCoordinate];
1237
    }
1238
1239
    /**
1240
     * Get an existing cell at a specific coordinate, or null.
1241
     *
1242
     * @param string $coordinate Coordinate of the cell, eg: 'A1'
1243
     *
1244
     * @return null|Cell Cell that was found or null
1245
     */
1246 58
    private function getCellOrNull(string $coordinate): ?Cell
1247
    {
1248
        // Check cell collection
1249 58
        if ($this->cellCollection->has($coordinate)) {
1250 58
            return $this->cellCollection->get($coordinate);
1251
        }
1252
1253
        return null;
1254
    }
1255
1256
    /**
1257
     * Create a new cell at the specified coordinate.
1258
     *
1259
     * @param string $coordinate Coordinate of the cell
1260
     *
1261
     * @return Cell Cell that was created
1262
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1263
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1264
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1265
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1266
     *              the active cell has changed.
1267
     */
1268 10057
    public function createNewCell(string $coordinate): Cell
1269
    {
1270 10057
        [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate);
1271 10057
        $cell = new Cell(null, DataType::TYPE_NULL, $this);
1272 10057
        $this->cellCollection->add($coordinate, $cell);
1273
1274
        // Coordinates
1275 10057
        if ($column > $this->cachedHighestColumn) {
1276 6890
            $this->cachedHighestColumn = $column;
1277
        }
1278 10057
        if ($row > $this->cachedHighestRow) {
1279 8451
            $this->cachedHighestRow = $row;
1280
        }
1281
1282
        // Cell needs appropriate xfIndex from dimensions records
1283
        //    but don't create dimension records if they don't already exist
1284 10057
        $rowDimension = $this->rowDimensions[$row] ?? null;
1285 10057
        $columnDimension = $this->columnDimensions[$columnString] ?? null;
1286
1287 10057
        $xfSet = false;
1288 10057
        if ($rowDimension !== null) {
1289 380
            $rowXf = (int) $rowDimension->getXfIndex();
1290 380
            if ($rowXf > 0) {
1291
                // then there is a row dimension with explicit style, assign it to the cell
1292 203
                $cell->setXfIndex($rowXf);
1293 203
                $xfSet = true;
1294
            }
1295
        }
1296 10057
        if (!$xfSet && $columnDimension !== null) {
1297 524
            $colXf = (int) $columnDimension->getXfIndex();
1298 524
            if ($colXf > 0) {
1299
                // then there is a column dimension, assign it to the cell
1300 214
                $cell->setXfIndex($colXf);
1301
            }
1302
        }
1303
1304 10057
        return $cell;
1305
    }
1306
1307
    /**
1308
     * Does the cell at a specific coordinate exist?
1309
     *
1310
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1311
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1312
     */
1313 9966
    public function cellExists(CellAddress|string|array $coordinate): bool
1314
    {
1315 9966
        $cellAddress = Validations::validateCellAddress($coordinate);
1316 9966
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
1317
1318 9966
        return $sheet->getCellCollection()->has($finalCoordinate);
1319
    }
1320
1321
    /**
1322
     * Get row dimension at a specific row.
1323
     *
1324
     * @param int $row Numeric index of the row
1325
     */
1326 540
    public function getRowDimension(int $row): RowDimension
1327
    {
1328
        // Get row dimension
1329 540
        if (!isset($this->rowDimensions[$row])) {
1330 540
            $this->rowDimensions[$row] = new RowDimension($row);
1331
1332 540
            $this->cachedHighestRow = max($this->cachedHighestRow, $row);
1333
        }
1334
1335 540
        return $this->rowDimensions[$row];
1336
    }
1337
1338 556
    public function rowDimensionExists(int $row): bool
1339
    {
1340 556
        return isset($this->rowDimensions[$row]);
1341
    }
1342
1343 34
    public function columnDimensionExists(string $column): bool
1344
    {
1345 34
        return isset($this->columnDimensions[$column]);
1346
    }
1347
1348
    /**
1349
     * Get column dimension at a specific column.
1350
     *
1351
     * @param string $column String index of the column eg: 'A'
1352
     */
1353 616
    public function getColumnDimension(string $column): ColumnDimension
1354
    {
1355
        // Uppercase coordinate
1356 616
        $column = strtoupper($column);
1357
1358
        // Fetch dimensions
1359 616
        if (!isset($this->columnDimensions[$column])) {
1360 616
            $this->columnDimensions[$column] = new ColumnDimension($column);
1361
1362 616
            $columnIndex = Coordinate::columnIndexFromString($column);
1363 616
            if ($this->cachedHighestColumn < $columnIndex) {
1364 436
                $this->cachedHighestColumn = $columnIndex;
1365
            }
1366
        }
1367
1368 616
        return $this->columnDimensions[$column];
1369
    }
1370
1371
    /**
1372
     * Get column dimension at a specific column by using numeric cell coordinates.
1373
     *
1374
     * @param int $columnIndex Numeric column coordinate of the cell
1375
     */
1376 97
    public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
1377
    {
1378 97
        return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
1379
    }
1380
1381
    /**
1382
     * Get styles.
1383
     *
1384
     * @return Style[]
1385
     */
1386 1
    public function getStyles(): array
1387
    {
1388 1
        return $this->styles;
1389
    }
1390
1391
    /**
1392
     * Get style for cell.
1393
     *
1394
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $cellCoordinate
1395
     *              A simple string containing a cell address like 'A1' or a cell range like 'A1:E10'
1396
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1397
     *              or a CellAddress or AddressRange object.
1398
     */
1399 10004
    public function getStyle(AddressRange|CellAddress|int|string|array $cellCoordinate): Style
1400
    {
1401 10004
        $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate);
1402
1403
        // set this sheet as active
1404 10004
        $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this));
1405
1406
        // set cell coordinate as active
1407 10004
        $this->setSelectedCells($cellCoordinate);
1408
1409 10004
        return $this->getParentOrThrow()->getCellXfSupervisor();
1410
    }
1411
1412
    /**
1413
     * Get conditional styles for a cell.
1414
     *
1415
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1416
     *          If a single cell is referenced, then the array of conditional styles will be returned if the cell is
1417
     *               included in a conditional style range.
1418
     *          If a range of cells is specified, then the styles will only be returned if the range matches the entire
1419
     *               range of the conditional.
1420
     *
1421
     * @return Conditional[]
1422
     */
1423 236
    public function getConditionalStyles(string $coordinate): array
1424
    {
1425 236
        $coordinate = strtoupper($coordinate);
1426 236
        if (str_contains($coordinate, ':')) {
1427 47
            return $this->conditionalStylesCollection[$coordinate] ?? [];
1428
        }
1429
1430 214
        $cell = $this->getCell($coordinate);
1431 214
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1432 201
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
1433 201
            foreach ($cellBlocks as $cellBlock) {
1434 201
                if ($cell->isInRange($cellBlock)) {
1435 194
                    return $this->conditionalStylesCollection[$conditionalRange];
1436
                }
1437
            }
1438
        }
1439
1440 43
        return [];
1441
    }
1442
1443 180
    public function getConditionalRange(string $coordinate): ?string
1444
    {
1445 180
        $coordinate = strtoupper($coordinate);
1446 180
        $cell = $this->getCell($coordinate);
1447 180
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1448 180
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
1449 180
            foreach ($cellBlocks as $cellBlock) {
1450 180
                if ($cell->isInRange($cellBlock)) {
1451 179
                    return $conditionalRange;
1452
                }
1453
            }
1454
        }
1455
1456 3
        return null;
1457
    }
1458
1459
    /**
1460
     * Do conditional styles exist for this cell?
1461
     *
1462
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1463
     *          If a single cell is specified, then this method will return true if that cell is included in a
1464
     *               conditional style range.
1465
     *          If a range of cells is specified, then true will only be returned if the range matches the entire
1466
     *               range of the conditional.
1467
     */
1468 22
    public function conditionalStylesExists(string $coordinate): bool
1469
    {
1470 22
        $coordinate = strtoupper($coordinate);
1471 22
        if (str_contains($coordinate, ':')) {
1472 11
            return isset($this->conditionalStylesCollection[$coordinate]);
1473
        }
1474
1475 11
        $cell = $this->getCell($coordinate);
1476 11
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1477 11
            if ($cell->isInRange($conditionalRange)) {
1478 7
                return true;
1479
            }
1480
        }
1481
1482 4
        return false;
1483
    }
1484
1485
    /**
1486
     * Removes conditional styles for a cell.
1487
     *
1488
     * @param string $coordinate eg: 'A1'
1489
     *
1490
     * @return $this
1491
     */
1492 44
    public function removeConditionalStyles(string $coordinate): static
1493
    {
1494 44
        unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
1495
1496 44
        return $this;
1497
    }
1498
1499
    /**
1500
     * Get collection of conditional styles.
1501
     */
1502 543
    public function getConditionalStylesCollection(): array
1503
    {
1504 543
        return $this->conditionalStylesCollection;
1505
    }
1506
1507
    /**
1508
     * Set conditional styles.
1509
     *
1510
     * @param string $coordinate eg: 'A1'
1511
     * @param Conditional[] $styles
1512
     *
1513
     * @return $this
1514
     */
1515 303
    public function setConditionalStyles(string $coordinate, array $styles): static
1516
    {
1517 303
        $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
1518
1519 303
        return $this;
1520
    }
1521
1522
    /**
1523
     * Duplicate cell style to a range of cells.
1524
     *
1525
     * Please note that this will overwrite existing cell styles for cells in range!
1526
     *
1527
     * @param Style $style Cell style to duplicate
1528
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1529
     *
1530
     * @return $this
1531
     */
1532 2
    public function duplicateStyle(Style $style, string $range): static
1533
    {
1534
        // Add the style to the workbook if necessary
1535 2
        $workbook = $this->getParentOrThrow();
1536 2
        if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) {
1537
            // there is already such cell Xf in our collection
1538 1
            $xfIndex = $existingStyle->getIndex();
1539
        } else {
1540
            // we don't have such a cell Xf, need to add
1541 2
            $workbook->addCellXf($style);
1542 2
            $xfIndex = $style->getIndex();
1543
        }
1544
1545
        // Calculate range outer borders
1546 2
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
1547
1548
        // Make sure we can loop upwards on rows and columns
1549 2
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1550
            $tmp = $rangeStart;
1551
            $rangeStart = $rangeEnd;
1552
            $rangeEnd = $tmp;
1553
        }
1554
1555
        // Loop through cells and apply styles
1556 2
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1557 2
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1558 2
                $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
1559
            }
1560
        }
1561
1562 2
        return $this;
1563
    }
1564
1565
    /**
1566
     * Duplicate conditional style to a range of cells.
1567
     *
1568
     * Please note that this will overwrite existing cell styles for cells in range!
1569
     *
1570
     * @param Conditional[] $styles Cell style to duplicate
1571
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1572
     *
1573
     * @return $this
1574
     */
1575 18
    public function duplicateConditionalStyle(array $styles, string $range = ''): static
1576
    {
1577 18
        foreach ($styles as $cellStyle) {
1578 18
            if (!($cellStyle instanceof Conditional)) {
1579
                throw new Exception('Style is not a conditional style');
1580
            }
1581
        }
1582
1583
        // Calculate range outer borders
1584 18
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
1585
1586
        // Make sure we can loop upwards on rows and columns
1587 18
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1588
            $tmp = $rangeStart;
1589
            $rangeStart = $rangeEnd;
1590
            $rangeEnd = $tmp;
1591
        }
1592
1593
        // Loop through cells and apply styles
1594 18
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1595 18
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1596 18
                $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
1597
            }
1598
        }
1599
1600 18
        return $this;
1601
    }
1602
1603
    /**
1604
     * Set break on a cell.
1605
     *
1606
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1607
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1608
     * @param int $break Break type (type of Worksheet::BREAK_*)
1609
     *
1610
     * @return $this
1611
     */
1612 29
    public function setBreak(CellAddress|string|array $coordinate, int $break, int $max = -1): static
1613
    {
1614 29
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1615
1616 29
        if ($break === self::BREAK_NONE) {
1617 7
            unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]);
1618 29
        } elseif ($break === self::BREAK_ROW) {
1619 21
            $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
1620 17
        } elseif ($break === self::BREAK_COLUMN) {
1621 17
            $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
1622
        }
1623
1624 29
        return $this;
1625
    }
1626
1627
    /**
1628
     * Get breaks.
1629
     *
1630
     * @return int[]
1631
     */
1632 615
    public function getBreaks(): array
1633
    {
1634 615
        $breaks = [];
1635
        /** @var callable $compareFunction */
1636 615
        $compareFunction = [self::class, 'compareRowBreaks'];
1637 615
        uksort($this->rowBreaks, $compareFunction);
1638 615
        foreach ($this->rowBreaks as $break) {
1639 10
            $breaks[$break->getCoordinate()] = self::BREAK_ROW;
1640
        }
1641
        /** @var callable $compareFunction */
1642 615
        $compareFunction = [self::class, 'compareColumnBreaks'];
1643 615
        uksort($this->columnBreaks, $compareFunction);
1644 615
        foreach ($this->columnBreaks as $break) {
1645 8
            $breaks[$break->getCoordinate()] = self::BREAK_COLUMN;
1646
        }
1647
1648 615
        return $breaks;
1649
    }
1650
1651
    /**
1652
     * Get row breaks.
1653
     *
1654
     * @return PageBreak[]
1655
     */
1656 466
    public function getRowBreaks(): array
1657
    {
1658
        /** @var callable $compareFunction */
1659 466
        $compareFunction = [self::class, 'compareRowBreaks'];
1660 466
        uksort($this->rowBreaks, $compareFunction);
1661
1662 466
        return $this->rowBreaks;
1663
    }
1664
1665 9
    protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int
1666
    {
1667 9
        $row1 = Coordinate::indexesFromString($coordinate1)[1];
1668 9
        $row2 = Coordinate::indexesFromString($coordinate2)[1];
1669
1670 9
        return $row1 - $row2;
1671
    }
1672
1673 5
    protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int
1674
    {
1675 5
        $column1 = Coordinate::indexesFromString($coordinate1)[0];
1676 5
        $column2 = Coordinate::indexesFromString($coordinate2)[0];
1677
1678 5
        return $column1 - $column2;
1679
    }
1680
1681
    /**
1682
     * Get column breaks.
1683
     *
1684
     * @return PageBreak[]
1685
     */
1686 465
    public function getColumnBreaks(): array
1687
    {
1688
        /** @var callable $compareFunction */
1689 465
        $compareFunction = [self::class, 'compareColumnBreaks'];
1690 465
        uksort($this->columnBreaks, $compareFunction);
1691
1692 465
        return $this->columnBreaks;
1693
    }
1694
1695
    /**
1696
     * Set merge on a cell range.
1697
     *
1698
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10'
1699
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1700
     *              or an AddressRange.
1701
     * @param string $behaviour How the merged cells should behave.
1702
     *               Possible values are:
1703
     *                   MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells
1704
     *                   MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells
1705
     *                   MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell
1706
     *
1707
     * @return $this
1708
     */
1709 162
    public function mergeCells(AddressRange|string|array $range, string $behaviour = self::MERGE_CELL_CONTENT_EMPTY): static
1710
    {
1711 162
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
1712
1713 161
        if (!str_contains($range, ':')) {
1714 1
            $range .= ":{$range}";
1715
        }
1716
1717 161
        if (preg_match('/^([A-Z]+)(\\d+):([A-Z]+)(\\d+)$/', $range, $matches) !== 1) {
1718 1
            throw new Exception('Merge must be on a valid range of cells.');
1719
        }
1720
1721 160
        $this->mergeCells[$range] = $range;
1722 160
        $firstRow = (int) $matches[2];
1723 160
        $lastRow = (int) $matches[4];
1724 160
        $firstColumn = $matches[1];
1725 160
        $lastColumn = $matches[3];
1726 160
        $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn);
1727 160
        $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn);
1728 160
        $numberRows = $lastRow - $firstRow;
1729 160
        $numberColumns = $lastColumnIndex - $firstColumnIndex;
1730
1731 160
        if ($numberRows === 1 && $numberColumns === 1) {
1732 30
            return $this;
1733
        }
1734
1735
        // create upper left cell if it does not already exist
1736 153
        $upperLeft = "{$firstColumn}{$firstRow}";
1737 153
        if (!$this->cellExists($upperLeft)) {
1738 31
            $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
1739
        }
1740
1741 153
        if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) {
1742
            // Blank out the rest of the cells in the range (if they exist)
1743 50
            if ($numberRows > $numberColumns) {
1744 12
                $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour);
1745
            } else {
1746 38
                $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour);
1747
            }
1748
        }
1749
1750 153
        return $this;
1751
    }
1752
1753 12
    private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1754
    {
1755 12
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
1756
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1757 12
            : [];
1758
1759 12
        foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) {
1760 12
            $iterator = $column->getCellIterator($firstRow);
1761 12
            $iterator->setIterateOnlyExistingCells(true);
1762 12
            foreach ($iterator as $cell) {
1763 12
                if ($cell !== null) {
1764 12
                    $row = $cell->getRow();
1765 12
                    if ($row > $lastRow) {
1766 7
                        break;
1767
                    }
1768 12
                    $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
1769
                }
1770
            }
1771
        }
1772
1773 12
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1774
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1775
        }
1776
    }
1777
1778 38
    private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1779
    {
1780 38
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
1781 4
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1782 34
            : [];
1783
1784 38
        foreach ($this->getRowIterator($firstRow, $lastRow) as $row) {
1785 38
            $iterator = $row->getCellIterator($firstColumn);
1786 38
            $iterator->setIterateOnlyExistingCells(true);
1787 38
            foreach ($iterator as $cell) {
1788 38
                if ($cell !== null) {
1789 38
                    $column = $cell->getColumn();
1790 38
                    $columnIndex = Coordinate::columnIndexFromString($column);
1791 38
                    if ($columnIndex > $lastColumnIndex) {
1792 8
                        break;
1793
                    }
1794 38
                    $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
1795
                }
1796
            }
1797
        }
1798
1799 38
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1800 4
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1801
        }
1802
    }
1803
1804 50
    public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array
1805
    {
1806 50
        if ($cell->getCoordinate() !== $upperLeft) {
1807 22
            Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance();
1808 22
            if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1809 4
                $cellValue = $cell->getFormattedValue();
1810 4
                if ($cellValue !== '') {
1811 4
                    $leftCellValue[] = $cellValue;
1812
                }
1813
            }
1814 22
            $cell->setValueExplicit(null, DataType::TYPE_NULL);
1815
        }
1816
1817 50
        return $leftCellValue;
1818
    }
1819
1820
    /**
1821
     * Remove merge on a cell range.
1822
     *
1823
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10'
1824
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1825
     *              or an AddressRange.
1826
     *
1827
     * @return $this
1828
     */
1829 23
    public function unmergeCells(AddressRange|string|array $range): static
1830
    {
1831 23
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
1832
1833 23
        if (str_contains($range, ':')) {
1834 22
            if (isset($this->mergeCells[$range])) {
1835 22
                unset($this->mergeCells[$range]);
1836
            } else {
1837
                throw new Exception('Cell range ' . $range . ' not known as merged.');
1838
            }
1839
        } else {
1840 1
            throw new Exception('Merge can only be removed from a range of cells.');
1841
        }
1842
1843 22
        return $this;
1844
    }
1845
1846
    /**
1847
     * Get merge cells array.
1848
     *
1849
     * @return string[]
1850
     */
1851 1103
    public function getMergeCells(): array
1852
    {
1853 1103
        return $this->mergeCells;
1854
    }
1855
1856
    /**
1857
     * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
1858
     * a single cell range.
1859
     *
1860
     * @param string[] $mergeCells
1861
     *
1862
     * @return $this
1863
     */
1864 93
    public function setMergeCells(array $mergeCells): static
1865
    {
1866 93
        $this->mergeCells = $mergeCells;
1867
1868 93
        return $this;
1869
    }
1870
1871
    /**
1872
     * Set protection on a cell or cell range.
1873
     *
1874
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10'
1875
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1876
     *              or a CellAddress or AddressRange object.
1877
     * @param string $password Password to unlock the protection
1878
     * @param bool $alreadyHashed If the password has already been hashed, set this to true
1879
     *
1880
     * @return $this
1881
     */
1882 24
    public function protectCells(AddressRange|CellAddress|int|string|array $range, string $password = '', bool $alreadyHashed = false, string $name = '', string $securityDescriptor = ''): static
1883
    {
1884 24
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
1885
1886 24
        if (!$alreadyHashed && $password !== '') {
1887 24
            $password = Shared\PasswordHasher::hashPassword($password);
1888
        }
1889 24
        $this->protectedCells[$range] = new ProtectedRange($range, $password, $name, $securityDescriptor);
1890
1891 24
        return $this;
1892
    }
1893
1894
    /**
1895
     * Remove protection on a cell or cell range.
1896
     *
1897
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10'
1898
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1899
     *              or a CellAddress or AddressRange object.
1900
     *
1901
     * @return $this
1902
     */
1903 20
    public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static
1904
    {
1905 20
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
1906
1907 20
        if (isset($this->protectedCells[$range])) {
1908 19
            unset($this->protectedCells[$range]);
1909
        } else {
1910 1
            throw new Exception('Cell range ' . $range . ' not known as protected.');
1911
        }
1912
1913 19
        return $this;
1914
    }
1915
1916
    /**
1917
     * Get password for protected cells.
1918
     *
1919
     * @return string[]
1920
     *
1921
     * @deprecated 2.0.1 use getProtectedCellRanges instead
1922
     * @see Worksheet::getProtectedCellRanges()
1923
     */
1924 94
    public function getProtectedCells(): array
1925
    {
1926 94
        $array = [];
1927 94
        foreach ($this->protectedCells as $key => $protectedRange) {
1928 18
            $array[$key] = $protectedRange->getPassword();
1929
        }
1930
1931 94
        return $array;
1932
    }
1933
1934
    /**
1935
     * Get protected cells.
1936
     *
1937
     * @return ProtectedRange[]
1938
     */
1939 465
    public function getProtectedCellRanges(): array
1940
    {
1941 465
        return $this->protectedCells;
1942
    }
1943
1944
    /**
1945
     * Get Autofilter.
1946
     */
1947 732
    public function getAutoFilter(): AutoFilter
1948
    {
1949 732
        return $this->autoFilter;
1950
    }
1951
1952
    /**
1953
     * Set AutoFilter.
1954
     *
1955
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|AutoFilter|string $autoFilterOrRange
1956
     *            A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
1957
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1958
     *              or an AddressRange.
1959
     *
1960
     * @return $this
1961
     */
1962 17
    public function setAutoFilter(AddressRange|string|array|AutoFilter $autoFilterOrRange): static
1963
    {
1964 17
        if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
1965
            $this->autoFilter = $autoFilterOrRange;
1966
        } else {
1967 17
            $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange));
1968
1969 17
            $this->autoFilter->setRange($cellRange);
1970
        }
1971
1972 17
        return $this;
1973
    }
1974
1975
    /**
1976
     * Remove autofilter.
1977
     */
1978 1
    public function removeAutoFilter(): self
1979
    {
1980 1
        $this->autoFilter->setRange('');
1981
1982 1
        return $this;
1983
    }
1984
1985
    /**
1986
     * Get collection of Tables.
1987
     *
1988
     * @return ArrayObject<int, Table>
1989
     */
1990 10013
    public function getTableCollection(): ArrayObject
1991
    {
1992 10013
        return $this->tableCollection;
1993
    }
1994
1995
    /**
1996
     * Add Table.
1997
     *
1998
     * @return $this
1999
     */
2000 97
    public function addTable(Table $table): self
2001
    {
2002 97
        $table->setWorksheet($this);
2003 97
        $this->tableCollection[] = $table;
2004
2005 97
        return $this;
2006
    }
2007
2008
    /**
2009
     * @return string[] array of Table names
2010
     */
2011 1
    public function getTableNames(): array
2012
    {
2013 1
        $tableNames = [];
2014
2015 1
        foreach ($this->tableCollection as $table) {
2016
            /** @var Table $table */
2017 1
            $tableNames[] = $table->getName();
2018
        }
2019
2020 1
        return $tableNames;
2021
    }
2022
2023
    /**
2024
     * @param string $name the table name to search
2025
     *
2026
     * @return null|Table The table from the tables collection, or null if not found
2027
     */
2028 91
    public function getTableByName(string $name): ?Table
2029
    {
2030 91
        $tableIndex = $this->getTableIndexByName($name);
2031
2032 91
        return ($tableIndex === null) ? null : $this->tableCollection[$tableIndex];
2033
    }
2034
2035
    /**
2036
     * @param string $name the table name to search
2037
     *
2038
     * @return null|int The index of the located table in the tables collection, or null if not found
2039
     */
2040 92
    protected function getTableIndexByName(string $name): ?int
2041
    {
2042 92
        $name = Shared\StringHelper::strToUpper($name);
2043 92
        foreach ($this->tableCollection as $index => $table) {
2044
            /** @var Table $table */
2045 62
            if (Shared\StringHelper::strToUpper($table->getName()) === $name) {
2046 61
                return $index;
2047
            }
2048
        }
2049
2050 36
        return null;
2051
    }
2052
2053
    /**
2054
     * Remove Table by name.
2055
     *
2056
     * @param string $name Table name
2057
     *
2058
     * @return $this
2059
     */
2060 1
    public function removeTableByName(string $name): self
2061
    {
2062 1
        $tableIndex = $this->getTableIndexByName($name);
2063
2064 1
        if ($tableIndex !== null) {
2065 1
            unset($this->tableCollection[$tableIndex]);
2066
        }
2067
2068 1
        return $this;
2069
    }
2070
2071
    /**
2072
     * Remove collection of Tables.
2073
     */
2074 1
    public function removeTableCollection(): self
2075
    {
2076 1
        $this->tableCollection = new ArrayObject();
2077
2078 1
        return $this;
2079
    }
2080
2081
    /**
2082
     * Get Freeze Pane.
2083
     */
2084 238
    public function getFreezePane(): ?string
2085
    {
2086 238
        return $this->freezePane;
2087
    }
2088
2089
    /**
2090
     * Freeze Pane.
2091
     *
2092
     * Examples:
2093
     *
2094
     *     - A2 will freeze the rows above cell A2 (i.e row 1)
2095
     *     - B1 will freeze the columns to the left of cell B1 (i.e column A)
2096
     *     - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
2097
     *
2098
     * @param null|array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
2099
     *            or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2100
     *        Passing a null value for this argument will clear any existing freeze pane for this worksheet.
2101
     * @param null|array{0: int, 1: int}|CellAddress|string $topLeftCell default position of the right bottom pane
2102
     *            Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]),
2103
     *            or a CellAddress object.
2104
     *
2105
     * @return $this
2106
     */
2107 49
    public function freezePane(null|CellAddress|string|array $coordinate, null|CellAddress|string|array $topLeftCell = null, bool $frozenSplit = false): static
2108
    {
2109 49
        $this->panes = [
2110 49
            'bottomRight' => null,
2111 49
            'bottomLeft' => null,
2112 49
            'topRight' => null,
2113 49
            'topLeft' => null,
2114 49
        ];
2115 49
        $cellAddress = ($coordinate !== null)
2116 49
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate))
2117 1
            : null;
2118 49
        if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) {
2119 1
            throw new Exception('Freeze pane can not be set on a range of cells.');
2120
        }
2121 48
        $topLeftCell = ($topLeftCell !== null)
2122 37
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell))
2123 36
            : null;
2124
2125 48
        if ($cellAddress !== null && $topLeftCell === null) {
2126 36
            $coordinate = Coordinate::coordinateFromString($cellAddress);
2127 36
            $topLeftCell = $coordinate[0] . $coordinate[1];
2128
        }
2129
2130 48
        $topLeftCell = "$topLeftCell";
2131 48
        $this->paneTopLeftCell = $topLeftCell;
2132
2133 48
        $this->freezePane = $cellAddress;
2134 48
        $this->topLeftCell = $topLeftCell;
2135 48
        if ($cellAddress === null) {
2136 1
            $this->paneState = '';
2137 1
            $this->xSplit = $this->ySplit = 0;
2138 1
            $this->activePane = '';
2139
        } else {
2140 48
            $coordinates = Coordinate::indexesFromString($cellAddress);
2141 48
            $this->xSplit = $coordinates[0] - 1;
2142 48
            $this->ySplit = $coordinates[1] - 1;
2143 48
            if ($this->xSplit > 0 || $this->ySplit > 0) {
2144 47
                $this->paneState = $frozenSplit ? self::PANE_FROZENSPLIT : self::PANE_FROZEN;
2145 47
                $this->setSelectedCellsActivePane();
2146
            } else {
2147 1
                $this->paneState = '';
2148 1
                $this->freezePane = null;
2149 1
                $this->activePane = '';
2150
            }
2151
        }
2152
2153 48
        return $this;
2154
    }
2155
2156 47
    public function setTopLeftCell(string $topLeftCell): self
2157
    {
2158 47
        $this->topLeftCell = $topLeftCell;
2159
2160 47
        return $this;
2161
    }
2162
2163
    /**
2164
     * Unfreeze Pane.
2165
     *
2166
     * @return $this
2167
     */
2168 1
    public function unfreezePane(): static
2169
    {
2170 1
        return $this->freezePane(null);
2171
    }
2172
2173
    /**
2174
     * Get the default position of the right bottom pane.
2175
     */
2176 416
    public function getTopLeftCell(): ?string
2177
    {
2178 416
        return $this->topLeftCell;
2179
    }
2180
2181 11
    public function getPaneTopLeftCell(): string
2182
    {
2183 11
        return $this->paneTopLeftCell;
2184
    }
2185
2186 26
    public function setPaneTopLeftCell(string $paneTopLeftCell): self
2187
    {
2188 26
        $this->paneTopLeftCell = $paneTopLeftCell;
2189
2190 26
        return $this;
2191
    }
2192
2193 404
    public function usesPanes(): bool
2194
    {
2195 404
        return $this->xSplit > 0 || $this->ySplit > 0;
2196
    }
2197
2198 2
    public function getPane(string $position): ?Pane
2199
    {
2200 2
        return $this->panes[$position] ?? null;
2201
    }
2202
2203 35
    public function setPane(string $position, ?Pane $pane): self
2204
    {
2205 35
        if (array_key_exists($position, $this->panes)) {
2206 35
            $this->panes[$position] = $pane;
2207
        }
2208
2209 35
        return $this;
2210
    }
2211
2212
    /** @return (null|Pane)[] */
2213 3
    public function getPanes(): array
2214
    {
2215 3
        return $this->panes;
2216
    }
2217
2218 14
    public function getActivePane(): string
2219
    {
2220 14
        return $this->activePane;
2221
    }
2222
2223 48
    public function setActivePane(string $activePane): self
2224
    {
2225 48
        $this->activePane = array_key_exists($activePane, $this->panes) ? $activePane : '';
2226
2227 48
        return $this;
2228
    }
2229
2230 11
    public function getXSplit(): int
2231
    {
2232 11
        return $this->xSplit;
2233
    }
2234
2235 11
    public function setXSplit(int $xSplit): self
2236
    {
2237 11
        $this->xSplit = $xSplit;
2238 11
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2239 1
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2240
        }
2241
2242 11
        return $this;
2243
    }
2244
2245 11
    public function getYSplit(): int
2246
    {
2247 11
        return $this->ySplit;
2248
    }
2249
2250 26
    public function setYSplit(int $ySplit): self
2251
    {
2252 26
        $this->ySplit = $ySplit;
2253 26
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2254 1
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2255
        }
2256
2257 26
        return $this;
2258
    }
2259
2260 21
    public function getPaneState(): string
2261
    {
2262 21
        return $this->paneState;
2263
    }
2264
2265
    public const PANE_FROZEN = 'frozen';
2266
    public const PANE_FROZENSPLIT = 'frozenSplit';
2267
    public const PANE_SPLIT = 'split';
2268
    private const VALIDPANESTATE = [self::PANE_FROZEN, self::PANE_SPLIT, self::PANE_FROZENSPLIT];
2269
    private const VALIDFROZENSTATE = [self::PANE_FROZEN, self::PANE_FROZENSPLIT];
2270
2271 26
    public function setPaneState(string $paneState): self
2272
    {
2273 26
        $this->paneState = in_array($paneState, self::VALIDPANESTATE, true) ? $paneState : '';
2274 26
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2275 25
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2276
        } else {
2277 3
            $this->freezePane = null;
2278
        }
2279
2280 26
        return $this;
2281
    }
2282
2283
    /**
2284
     * Insert a new row, updating all possible related data.
2285
     *
2286
     * @param int $before Insert before this row number
2287
     * @param int $numberOfRows Number of new rows to insert
2288
     *
2289
     * @return $this
2290
     */
2291 37
    public function insertNewRowBefore(int $before, int $numberOfRows = 1): static
2292
    {
2293 37
        if ($before >= 1) {
2294 36
            $objReferenceHelper = ReferenceHelper::getInstance();
2295 36
            $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
2296
        } else {
2297 1
            throw new Exception('Rows can only be inserted before at least row 1.');
2298
        }
2299
2300 36
        return $this;
2301
    }
2302
2303
    /**
2304
     * Insert a new column, updating all possible related data.
2305
     *
2306
     * @param string $before Insert before this column Name, eg: 'A'
2307
     * @param int $numberOfColumns Number of new columns to insert
2308
     *
2309
     * @return $this
2310
     */
2311 43
    public function insertNewColumnBefore(string $before, int $numberOfColumns = 1): static
2312
    {
2313 43
        if (!is_numeric($before)) {
2314 42
            $objReferenceHelper = ReferenceHelper::getInstance();
2315 42
            $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
2316
        } else {
2317 1
            throw new Exception('Column references should not be numeric.');
2318
        }
2319
2320 42
        return $this;
2321
    }
2322
2323
    /**
2324
     * Insert a new column, updating all possible related data.
2325
     *
2326
     * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell)
2327
     * @param int $numberOfColumns Number of new columns to insert
2328
     *
2329
     * @return $this
2330
     */
2331 2
    public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1): static
2332
    {
2333 2
        if ($beforeColumnIndex >= 1) {
2334 1
            return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
2335
        }
2336
2337 1
        throw new Exception('Columns can only be inserted before at least column A (1).');
2338
    }
2339
2340
    /**
2341
     * Delete a row, updating all possible related data.
2342
     *
2343
     * @param int $row Remove rows, starting with this row number
2344
     * @param int $numberOfRows Number of rows to remove
2345
     *
2346
     * @return $this
2347
     */
2348 42
    public function removeRow(int $row, int $numberOfRows = 1): static
2349
    {
2350 42
        if ($row < 1) {
2351 1
            throw new Exception('Rows to be deleted should at least start from row 1.');
2352
        }
2353
2354 41
        $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows);
2355 41
        $highestRow = $this->getHighestDataRow();
2356 41
        $removedRowsCounter = 0;
2357
2358 41
        for ($r = 0; $r < $numberOfRows; ++$r) {
2359 41
            if ($row + $r <= $highestRow) {
2360 37
                $this->cellCollection->removeRow($row + $r);
2361 37
                ++$removedRowsCounter;
2362
            }
2363
        }
2364
2365 41
        $objReferenceHelper = ReferenceHelper::getInstance();
2366 41
        $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
2367 41
        for ($r = 0; $r < $removedRowsCounter; ++$r) {
2368 37
            $this->cellCollection->removeRow($highestRow);
2369 37
            --$highestRow;
2370
        }
2371
2372 41
        $this->rowDimensions = $holdRowDimensions;
2373
2374 41
        return $this;
2375
    }
2376
2377 41
    private function removeRowDimensions(int $row, int $numberOfRows): array
2378
    {
2379 41
        $highRow = $row + $numberOfRows - 1;
2380 41
        $holdRowDimensions = [];
2381 41
        foreach ($this->rowDimensions as $rowDimension) {
2382 4
            $num = $rowDimension->getRowIndex();
2383 4
            if ($num < $row) {
2384 3
                $holdRowDimensions[$num] = $rowDimension;
2385 4
            } elseif ($num > $highRow) {
2386 4
                $num -= $numberOfRows;
2387 4
                $cloneDimension = clone $rowDimension;
2388 4
                $cloneDimension->setRowIndex($num);
2389 4
                $holdRowDimensions[$num] = $cloneDimension;
2390
            }
2391
        }
2392
2393 41
        return $holdRowDimensions;
2394
    }
2395
2396
    /**
2397
     * Remove a column, updating all possible related data.
2398
     *
2399
     * @param string $column Remove columns starting with this column name, eg: 'A'
2400
     * @param int $numberOfColumns Number of columns to remove
2401
     *
2402
     * @return $this
2403
     */
2404 34
    public function removeColumn(string $column, int $numberOfColumns = 1): static
2405
    {
2406 34
        if (is_numeric($column)) {
2407 1
            throw new Exception('Column references should not be numeric.');
2408
        }
2409
2410 33
        $highestColumn = $this->getHighestDataColumn();
2411 33
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
2412 33
        $pColumnIndex = Coordinate::columnIndexFromString($column);
2413
2414 33
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
2415
2416 33
        $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
2417 33
        $objReferenceHelper = ReferenceHelper::getInstance();
2418 33
        $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
2419
2420 33
        $this->columnDimensions = $holdColumnDimensions;
2421
2422 33
        if ($pColumnIndex > $highestColumnIndex) {
2423 2
            return $this;
2424
        }
2425
2426 31
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
2427
2428 31
        for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
2429 31
            $this->cellCollection->removeColumn($highestColumn);
2430 31
            $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
2431
        }
2432
2433 31
        $this->garbageCollect();
2434
2435 31
        return $this;
2436
    }
2437
2438 33
    private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array
2439
    {
2440 33
        $highCol = $pColumnIndex + $numberOfColumns - 1;
2441 33
        $holdColumnDimensions = [];
2442 33
        foreach ($this->columnDimensions as $columnDimension) {
2443 18
            $num = $columnDimension->getColumnNumeric();
2444 18
            if ($num < $pColumnIndex) {
2445 18
                $str = $columnDimension->getColumnIndex();
2446 18
                $holdColumnDimensions[$str] = $columnDimension;
2447 18
            } elseif ($num > $highCol) {
2448 18
                $cloneDimension = clone $columnDimension;
2449 18
                $cloneDimension->setColumnNumeric($num - $numberOfColumns);
2450 18
                $str = $cloneDimension->getColumnIndex();
2451 18
                $holdColumnDimensions[$str] = $cloneDimension;
2452
            }
2453
        }
2454
2455 33
        return $holdColumnDimensions;
2456
    }
2457
2458
    /**
2459
     * Remove a column, updating all possible related data.
2460
     *
2461
     * @param int $columnIndex Remove starting with this column Index (numeric column coordinate)
2462
     * @param int $numColumns Number of columns to remove
2463
     *
2464
     * @return $this
2465
     */
2466 2
    public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static
2467
    {
2468 2
        if ($columnIndex >= 1) {
2469 1
            return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2470
        }
2471
2472 1
        throw new Exception('Columns to be deleted should at least start from column A (1)');
2473
    }
2474
2475
    /**
2476
     * Show gridlines?
2477
     */
2478 971
    public function getShowGridlines(): bool
2479
    {
2480 971
        return $this->showGridlines;
2481
    }
2482
2483
    /**
2484
     * Set show gridlines.
2485
     *
2486
     * @param bool $showGridLines Show gridlines (true/false)
2487
     *
2488
     * @return $this
2489
     */
2490 813
    public function setShowGridlines(bool $showGridLines): self
2491
    {
2492 813
        $this->showGridlines = $showGridLines;
2493
2494 813
        return $this;
2495
    }
2496
2497
    /**
2498
     * Print gridlines?
2499
     */
2500 976
    public function getPrintGridlines(): bool
2501
    {
2502 976
        return $this->printGridlines;
2503
    }
2504
2505
    /**
2506
     * Set print gridlines.
2507
     *
2508
     * @param bool $printGridLines Print gridlines (true/false)
2509
     *
2510
     * @return $this
2511
     */
2512 562
    public function setPrintGridlines(bool $printGridLines): self
2513
    {
2514 562
        $this->printGridlines = $printGridLines;
2515
2516 562
        return $this;
2517
    }
2518
2519
    /**
2520
     * Show row and column headers?
2521
     */
2522 462
    public function getShowRowColHeaders(): bool
2523
    {
2524 462
        return $this->showRowColHeaders;
2525
    }
2526
2527
    /**
2528
     * Set show row and column headers.
2529
     *
2530
     * @param bool $showRowColHeaders Show row and column headers (true/false)
2531
     *
2532
     * @return $this
2533
     */
2534 354
    public function setShowRowColHeaders(bool $showRowColHeaders): self
2535
    {
2536 354
        $this->showRowColHeaders = $showRowColHeaders;
2537
2538 354
        return $this;
2539
    }
2540
2541
    /**
2542
     * Show summary below? (Row/Column outlining).
2543
     */
2544 463
    public function getShowSummaryBelow(): bool
2545
    {
2546 463
        return $this->showSummaryBelow;
2547
    }
2548
2549
    /**
2550
     * Set show summary below.
2551
     *
2552
     * @param bool $showSummaryBelow Show summary below (true/false)
2553
     *
2554
     * @return $this
2555
     */
2556 359
    public function setShowSummaryBelow(bool $showSummaryBelow): self
2557
    {
2558 359
        $this->showSummaryBelow = $showSummaryBelow;
2559
2560 359
        return $this;
2561
    }
2562
2563
    /**
2564
     * Show summary right? (Row/Column outlining).
2565
     */
2566 463
    public function getShowSummaryRight(): bool
2567
    {
2568 463
        return $this->showSummaryRight;
2569
    }
2570
2571
    /**
2572
     * Set show summary right.
2573
     *
2574
     * @param bool $showSummaryRight Show summary right (true/false)
2575
     *
2576
     * @return $this
2577
     */
2578 359
    public function setShowSummaryRight(bool $showSummaryRight): self
2579
    {
2580 359
        $this->showSummaryRight = $showSummaryRight;
2581
2582 359
        return $this;
2583
    }
2584
2585
    /**
2586
     * Get comments.
2587
     *
2588
     * @return Comment[]
2589
     */
2590 1006
    public function getComments(): array
2591
    {
2592 1006
        return $this->comments;
2593
    }
2594
2595
    /**
2596
     * Set comments array for the entire sheet.
2597
     *
2598
     * @param Comment[] $comments
2599
     *
2600
     * @return $this
2601
     */
2602 93
    public function setComments(array $comments): self
2603
    {
2604 93
        $this->comments = $comments;
2605
2606 93
        return $this;
2607
    }
2608
2609
    /**
2610
     * Remove comment from cell.
2611
     *
2612
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2613
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2614
     *
2615
     * @return $this
2616
     */
2617 46
    public function removeComment(CellAddress|string|array $cellCoordinate): self
2618
    {
2619 46
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2620
2621 46
        if (Coordinate::coordinateIsRange($cellAddress)) {
2622 1
            throw new Exception('Cell coordinate string can not be a range of cells.');
2623 45
        } elseif (str_contains($cellAddress, '$')) {
2624 1
            throw new Exception('Cell coordinate string must not be absolute.');
2625 44
        } elseif ($cellAddress == '') {
2626 1
            throw new Exception('Cell coordinate can not be zero-length string.');
2627
        }
2628
        // Check if we have a comment for this cell and delete it
2629 43
        if (isset($this->comments[$cellAddress])) {
2630 2
            unset($this->comments[$cellAddress]);
2631
        }
2632
2633 43
        return $this;
2634
    }
2635
2636
    /**
2637
     * Get comment for cell.
2638
     *
2639
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2640
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2641
     */
2642 108
    public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment
2643
    {
2644 108
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2645
2646 108
        if (Coordinate::coordinateIsRange($cellAddress)) {
2647 1
            throw new Exception('Cell coordinate string can not be a range of cells.');
2648 107
        } elseif (str_contains($cellAddress, '$')) {
2649 1
            throw new Exception('Cell coordinate string must not be absolute.');
2650 106
        } elseif ($cellAddress == '') {
2651 1
            throw new Exception('Cell coordinate can not be zero-length string.');
2652
        }
2653
2654
        // Check if we already have a comment for this cell.
2655 105
        if (isset($this->comments[$cellAddress])) {
2656 72
            return $this->comments[$cellAddress];
2657
        }
2658
2659
        // If not, create a new comment.
2660 105
        $newComment = new Comment();
2661 105
        if ($attachNew) {
2662 105
            $this->comments[$cellAddress] = $newComment;
2663
        }
2664
2665 105
        return $newComment;
2666
    }
2667
2668
    /**
2669
     * Get active cell.
2670
     *
2671
     * @return string Example: 'A1'
2672
     */
2673 10052
    public function getActiveCell(): string
2674
    {
2675 10052
        return $this->activeCell;
2676
    }
2677
2678
    /**
2679
     * Get selected cells.
2680
     */
2681 10092
    public function getSelectedCells(): string
2682
    {
2683 10092
        return $this->selectedCells;
2684
    }
2685
2686
    /**
2687
     * Selected cell.
2688
     *
2689
     * @param string $coordinate Cell (i.e. A1)
2690
     *
2691
     * @return $this
2692
     */
2693 36
    public function setSelectedCell(string $coordinate): static
2694
    {
2695 36
        return $this->setSelectedCells($coordinate);
2696
    }
2697
2698
    /**
2699
     * Select a range of cells.
2700
     *
2701
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $coordinate A simple string containing a Cell range like 'A1:E10'
2702
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2703
     *              or a CellAddress or AddressRange object.
2704
     *
2705
     * @return $this
2706
     */
2707 10071
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
2708
    {
2709 10071
        if (is_string($coordinate)) {
2710 10071
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
2711
        }
2712 10071
        $coordinate = Validations::validateCellOrCellRange($coordinate);
2713
2714 10071
        if (Coordinate::coordinateIsRange($coordinate)) {
2715 475
            [$first] = Coordinate::splitRange($coordinate);
2716 475
            $this->activeCell = $first[0];
2717
        } else {
2718 10042
            $this->activeCell = $coordinate;
2719
        }
2720 10071
        $this->selectedCells = $coordinate;
2721 10071
        $this->setSelectedCellsActivePane();
2722
2723 10071
        return $this;
2724
    }
2725
2726 10072
    private function setSelectedCellsActivePane(): void
2727
    {
2728 10072
        if (!empty($this->freezePane)) {
2729 47
            $coordinateC = Coordinate::indexesFromString($this->freezePane);
2730 47
            $coordinateT = Coordinate::indexesFromString($this->activeCell);
2731 47
            if ($coordinateC[0] === 1) {
2732 26
                $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft';
2733 23
            } elseif ($coordinateC[1] === 1) {
2734 3
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2735 21
            } elseif ($coordinateT[1] <= $coordinateC[1]) {
2736 21
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2737
            } else {
2738 10
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight';
2739
            }
2740 47
            $this->setActivePane($activePane);
2741 47
            $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell);
2742
        }
2743
    }
2744
2745
    /**
2746
     * Get right-to-left.
2747
     */
2748 462
    public function getRightToLeft(): bool
2749
    {
2750 462
        return $this->rightToLeft;
2751
    }
2752
2753
    /**
2754
     * Set right-to-left.
2755
     *
2756
     * @param bool $value Right-to-left true/false
2757
     *
2758
     * @return $this
2759
     */
2760 127
    public function setRightToLeft(bool $value): static
2761
    {
2762 127
        $this->rightToLeft = $value;
2763
2764 127
        return $this;
2765
    }
2766
2767
    /**
2768
     * Fill worksheet from values in array.
2769
     *
2770
     * @param array $source Source array
2771
     * @param mixed $nullValue Value in source array that stands for blank cell
2772
     * @param string $startCell Insert array starting from this cell address as the top left coordinate
2773
     * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2774
     *
2775
     * @return $this
2776
     */
2777 742
    public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static
2778
    {
2779
        //    Convert a 1-D array to 2-D (for ease of looping)
2780 742
        if (!is_array(end($source))) {
2781 42
            $source = [$source];
2782
        }
2783
2784
        // start coordinate
2785 742
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
2786
2787
        // Loop through $source
2788 742
        if ($strictNullComparison) {
2789 346
            foreach ($source as $rowData) {
2790 346
                $currentColumn = $startColumn;
2791 346
                foreach ($rowData as $cellValue) {
2792 346
                    if ($cellValue !== $nullValue) {
2793
                        // Set cell value
2794 346
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2795
                    }
2796 346
                    ++$currentColumn;
2797
                }
2798 346
                ++$startRow;
2799
            }
2800
        } else {
2801 397
            foreach ($source as $rowData) {
2802 397
                $currentColumn = $startColumn;
2803 397
                foreach ($rowData as $cellValue) {
2804 396
                    if ($cellValue != $nullValue) {
2805
                        // Set cell value
2806 390
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2807
                    }
2808 396
                    ++$currentColumn;
2809
                }
2810 397
                ++$startRow;
2811
            }
2812
        }
2813
2814 742
        return $this;
2815
    }
2816
2817
    /**
2818
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2819
     *
2820
     * @throws Exception
2821
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2822
     */
2823 166
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue): mixed
2824
    {
2825 166
        $returnValue = $nullValue;
2826
2827 166
        if ($cell->getValue() !== null) {
2828 166
            if ($cell->getValue() instanceof RichText) {
2829 4
                $returnValue = $cell->getValue()->getPlainText();
2830
            } else {
2831 166
                $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue();
2832
            }
2833
2834 166
            if ($formatData) {
2835 106
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
2836
                /** @var null|bool|float|int|RichText|string */
2837 106
                $returnValuex = $returnValue;
2838 106
                $returnValue = NumberFormat::toFormattedString(
2839 106
                    $returnValuex,
2840 106
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL
2841 106
                );
2842
            }
2843
        }
2844
2845 166
        return $returnValue;
2846
    }
2847
2848
    /**
2849
     * Create array from a range of cells.
2850
     *
2851
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2852
     * @param bool $calculateFormulas Should formulas be calculated?
2853
     * @param bool $formatData Should formatting be applied to cell values?
2854
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2855
     *                             True - Return rows and columns indexed by their actual row and column IDs
2856
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2857
     *                            True - Don't return values for rows/columns that are defined as hidden.
2858
     */
2859 139
    public function rangeToArray(
2860
        string $range,
2861
        mixed $nullValue = null,
2862
        bool $calculateFormulas = true,
2863
        bool $formatData = true,
2864
        bool $returnCellRef = false,
2865
        bool $ignoreHidden = false,
2866
        bool $reduceArrays = false
2867
    ): array {
2868 139
        $returnValue = [];
2869
2870
        // Loop through rows
2871 139
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
2872 139
            $returnValue[$rowRef] = $rowArray;
2873
        }
2874
2875
        // Return
2876 139
        return $returnValue;
2877
    }
2878
2879
    /**
2880
     * Create array from a range of cells, yielding each row in turn.
2881
     *
2882
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2883
     * @param bool $calculateFormulas Should formulas be calculated?
2884
     * @param bool $formatData Should formatting be applied to cell values?
2885
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2886
     *                             True - Return rows and columns indexed by their actual row and column IDs
2887
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2888
     *                            True - Don't return values for rows/columns that are defined as hidden.
2889
     *
2890
     * @return Generator<array>
2891
     */
2892 166
    public function rangeToArrayYieldRows(
2893
        string $range,
2894
        mixed $nullValue = null,
2895
        bool $calculateFormulas = true,
2896
        bool $formatData = true,
2897
        bool $returnCellRef = false,
2898
        bool $ignoreHidden = false,
2899
        bool $reduceArrays = false
2900
    ) {
2901 166
        $range = Validations::validateCellOrCellRange($range);
2902
2903
        //    Identify the range that we need to extract from the worksheet
2904 166
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
2905 166
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
2906 166
        $minRow = $rangeStart[1];
2907 166
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
2908 166
        $maxRow = $rangeEnd[1];
2909 166
        $minColInt = $rangeStart[0];
2910 166
        $maxColInt = $rangeEnd[0];
2911
2912 166
        ++$maxCol;
2913
        /** @var array<string, bool> */
2914 166
        $hiddenColumns = [];
2915 166
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
2916 166
        $hideColumns = !empty($hiddenColumns);
2917
2918 166
        $keys = $this->cellCollection->getSortedCoordinatesInt();
2919 166
        $keyIndex = 0;
2920 166
        $keysCount = count($keys);
2921
        // Loop through rows
2922 166
        for ($row = $minRow; $row <= $maxRow; ++$row) {
2923 166
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
2924 4
                continue;
2925
            }
2926 166
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
2927 166
            $returnValue = $nullRow;
2928
2929 166
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
2930 166
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
2931 166
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
2932 49
                ++$keyIndex;
2933
            }
2934 166
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
2935 166
                $key = $keys[$keyIndex];
2936 166
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
2937 166
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
2938 166
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
2939 166
                    $col = Coordinate::stringFromColumnIndex($thisCol);
2940 166
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
2941 166
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
2942 166
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
2943 166
                        if ($cell !== null) {
2944 166
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue);
2945 166
                            if ($reduceArrays) {
2946 21
                                while (is_array($value)) {
2947 18
                                    $value = array_shift($value);
2948
                                }
2949
                            }
2950 166
                            if ($value !== $nullValue) {
2951 166
                                $returnValue[$columnRef] = $value;
2952
                            }
2953
                        }
2954
                    }
2955
                }
2956 166
                ++$keyIndex;
2957
            }
2958
2959 166
            yield $rowRef => $returnValue;
2960
        }
2961
    }
2962
2963
    /**
2964
     * Prepare a row data filled with null values to deduplicate the memory areas for empty rows.
2965
     *
2966
     * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
2967
     * @param string $minCol Start column of the range
2968
     * @param string $maxCol End column of the range
2969
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2970
     *                              True - Return rows and columns indexed by their actual row and column IDs
2971
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2972
     *                             True - Don't return values for rows/columns that are defined as hidden.
2973
     * @param array<string, bool> $hiddenColumns
2974
     */
2975 166
    private function buildNullRow(
2976
        mixed $nullValue,
2977
        string $minCol,
2978
        string $maxCol,
2979
        bool $returnCellRef,
2980
        bool $ignoreHidden,
2981
        array &$hiddenColumns
2982
    ): array {
2983 166
        $nullRow = [];
2984 166
        $c = -1;
2985 166
        for ($col = $minCol; $col !== $maxCol; ++$col) {
2986 166
            if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) {
2987 2
                $hiddenColumns[$col] = true;
2988
            } else {
2989 166
                $columnRef = $returnCellRef ? $col : ++$c;
2990 166
                $nullRow[$columnRef] = $nullValue;
2991
            }
2992
        }
2993
2994 166
        return $nullRow;
2995
    }
2996
2997 17
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
2998
    {
2999 17
        $namedRange = DefinedName::resolveName($definedName, $this);
3000 17
        if ($namedRange === null) {
3001 6
            if ($returnNullIfInvalid) {
3002 5
                return null;
3003
            }
3004
3005 1
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
3006
        }
3007
3008 11
        if ($namedRange->isFormula()) {
3009
            if ($returnNullIfInvalid) {
3010
                return null;
3011
            }
3012
3013
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
3014
        }
3015
3016 11
        if ($namedRange->getLocalOnly()) {
3017 2
            $worksheet = $namedRange->getWorksheet();
3018 2
            if ($worksheet === null || $this->hash !== $worksheet->getHashInt()) {
3019
                if ($returnNullIfInvalid) {
3020
                    return null;
3021
                }
3022
3023
                throw new Exception(
3024
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
3025
                );
3026
            }
3027
        }
3028
3029 11
        return $namedRange;
3030
    }
3031
3032
    /**
3033
     * Create array from a range of cells.
3034
     *
3035
     * @param string $definedName The Named Range that should be returned
3036
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3037
     * @param bool $calculateFormulas Should formulas be calculated?
3038
     * @param bool $formatData Should formatting be applied to cell values?
3039
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3040
     *                             True - Return rows and columns indexed by their actual row and column IDs
3041
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3042
     *                            True - Don't return values for rows/columns that are defined as hidden.
3043
     */
3044 2
    public function namedRangeToArray(
3045
        string $definedName,
3046
        mixed $nullValue = null,
3047
        bool $calculateFormulas = true,
3048
        bool $formatData = true,
3049
        bool $returnCellRef = false,
3050
        bool $ignoreHidden = false,
3051
        bool $reduceArrays = false
3052
    ): array {
3053 2
        $retVal = [];
3054 2
        $namedRange = $this->validateNamedRange($definedName);
3055 1
        if ($namedRange !== null) {
3056 1
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
3057 1
            $cellRange = str_replace('$', '', $cellRange);
3058 1
            $workSheet = $namedRange->getWorksheet();
3059 1
            if ($workSheet !== null) {
3060 1
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3061
            }
3062
        }
3063
3064 1
        return $retVal;
3065
    }
3066
3067
    /**
3068
     * Create array from worksheet.
3069
     *
3070
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3071
     * @param bool $calculateFormulas Should formulas be calculated?
3072
     * @param bool $formatData Should formatting be applied to cell values?
3073
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3074
     *                             True - Return rows and columns indexed by their actual row and column IDs
3075
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3076
     *                            True - Don't return values for rows/columns that are defined as hidden.
3077
     */
3078 72
    public function toArray(
3079
        mixed $nullValue = null,
3080
        bool $calculateFormulas = true,
3081
        bool $formatData = true,
3082
        bool $returnCellRef = false,
3083
        bool $ignoreHidden = false,
3084
        bool $reduceArrays = false
3085
    ): array {
3086
        // Garbage collect...
3087 72
        $this->garbageCollect();
3088 72
        $this->calculateArrays($calculateFormulas);
3089
3090
        //    Identify the range that we need to extract from the worksheet
3091 72
        $maxCol = $this->getHighestColumn();
3092 72
        $maxRow = $this->getHighestRow();
3093
3094
        // Return
3095 72
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3096
    }
3097
3098
    /**
3099
     * Get row iterator.
3100
     *
3101
     * @param int $startRow The row number at which to start iterating
3102
     * @param ?int $endRow The row number at which to stop iterating
3103
     */
3104 83
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
3105
    {
3106 83
        return new RowIterator($this, $startRow, $endRow);
3107
    }
3108
3109
    /**
3110
     * Get column iterator.
3111
     *
3112
     * @param string $startColumn The column address at which to start iterating
3113
     * @param ?string $endColumn The column address at which to stop iterating
3114
     */
3115 19
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
3116
    {
3117 19
        return new ColumnIterator($this, $startColumn, $endColumn);
3118
    }
3119
3120
    /**
3121
     * Run PhpSpreadsheet garbage collector.
3122
     *
3123
     * @return $this
3124
     */
3125 1083
    public function garbageCollect(): static
3126
    {
3127
        // Flush cache
3128 1083
        $this->cellCollection->get('A1');
3129
3130
        // Lookup highest column and highest row if cells are cleaned
3131 1083
        $colRow = $this->cellCollection->getHighestRowAndColumn();
3132 1083
        $highestRow = $colRow['row'];
3133 1083
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
3134
3135
        // Loop through column dimensions
3136 1083
        foreach ($this->columnDimensions as $dimension) {
3137 147
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
3138
        }
3139
3140
        // Loop through row dimensions
3141 1083
        foreach ($this->rowDimensions as $dimension) {
3142 90
            $highestRow = max($highestRow, $dimension->getRowIndex());
3143
        }
3144
3145
        // Cache values
3146 1083
        if ($highestColumn < 1) {
3147
            $this->cachedHighestColumn = 1;
3148
        } else {
3149 1083
            $this->cachedHighestColumn = $highestColumn;
3150
        }
3151 1083
        $this->cachedHighestRow = $highestRow;
3152
3153
        // Return
3154 1083
        return $this;
3155
    }
3156
3157
    /**
3158
     * @deprecated 3.5.0 use getHashInt instead.
3159
     */
3160
    public function getHashCode(): string
3161
    {
3162
        return (string) $this->hash;
3163
    }
3164
3165 10379
    public function getHashInt(): int
3166
    {
3167 10379
        return $this->hash;
3168
    }
3169
3170
    /**
3171
     * Extract worksheet title from range.
3172
     *
3173
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3174
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3175
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3176
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3177
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3178
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3179
     *
3180
     * @param ?string $range Range to extract title from
3181
     * @param bool $returnRange Return range? (see example)
3182
     *
3183
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3184
     */
3185 10273
    public static function extractSheetTitle(?string $range, bool $returnRange = false): array|null|string
3186
    {
3187 10273
        if (empty($range)) {
3188 13
            return $returnRange ? [null, null] : null;
3189
        }
3190
3191
        // Sheet title included?
3192 10271
        if (($sep = strrpos($range, '!')) === false) {
3193 10245
            return $returnRange ? ['', $range] : '';
3194
        }
3195
3196 1324
        if ($returnRange) {
3197 1324
            return [substr($range, 0, $sep), substr($range, $sep + 1)];
3198
        }
3199
3200 7
        return substr($range, $sep + 1);
3201
    }
3202
3203
    /**
3204
     * Get hyperlink.
3205
     *
3206
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3207
     */
3208 87
    public function getHyperlink(string $cellCoordinate): Hyperlink
3209
    {
3210
        // return hyperlink if we already have one
3211 87
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
3212 40
            return $this->hyperlinkCollection[$cellCoordinate];
3213
        }
3214
3215
        // else create hyperlink
3216 87
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
3217
3218 87
        return $this->hyperlinkCollection[$cellCoordinate];
3219
    }
3220
3221
    /**
3222
     * Set hyperlink.
3223
     *
3224
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3225
     *
3226
     * @return $this
3227
     */
3228 44
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static
3229
    {
3230 44
        if ($hyperlink === null) {
3231 43
            unset($this->hyperlinkCollection[$cellCoordinate]);
3232
        } else {
3233 21
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
3234
        }
3235
3236 44
        return $this;
3237
    }
3238
3239
    /**
3240
     * Hyperlink at a specific coordinate exists?
3241
     *
3242
     * @param string $coordinate eg: 'A1'
3243
     */
3244 523
    public function hyperlinkExists(string $coordinate): bool
3245
    {
3246 523
        return isset($this->hyperlinkCollection[$coordinate]);
3247
    }
3248
3249
    /**
3250
     * Get collection of hyperlinks.
3251
     *
3252
     * @return Hyperlink[]
3253
     */
3254 539
    public function getHyperlinkCollection(): array
3255
    {
3256 539
        return $this->hyperlinkCollection;
3257
    }
3258
3259
    /**
3260
     * Get data validation.
3261
     *
3262
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3263
     */
3264 31
    public function getDataValidation(string $cellCoordinate): DataValidation
3265
    {
3266
        // return data validation if we already have one
3267 31
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
3268 20
            return $this->dataValidationCollection[$cellCoordinate];
3269
        }
3270
3271
        // else create data validation
3272 30
        $this->dataValidationCollection[$cellCoordinate] = new DataValidation();
3273
3274 30
        return $this->dataValidationCollection[$cellCoordinate];
3275
    }
3276
3277
    /**
3278
     * Set data validation.
3279
     *
3280
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3281
     *
3282
     * @return $this
3283
     */
3284 50
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
3285
    {
3286 50
        if ($dataValidation === null) {
3287 45
            unset($this->dataValidationCollection[$cellCoordinate]);
3288
        } else {
3289 9
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
3290
        }
3291
3292 50
        return $this;
3293
    }
3294
3295
    /**
3296
     * Data validation at a specific coordinate exists?
3297
     *
3298
     * @param string $coordinate eg: 'A1'
3299
     */
3300 18
    public function dataValidationExists(string $coordinate): bool
3301
    {
3302 18
        return isset($this->dataValidationCollection[$coordinate]);
3303
    }
3304
3305
    /**
3306
     * Get collection of data validations.
3307
     *
3308
     * @return DataValidation[]
3309
     */
3310 539
    public function getDataValidationCollection(): array
3311
    {
3312 539
        return $this->dataValidationCollection;
3313
    }
3314
3315
    /**
3316
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3317
     *
3318
     * @return string Adjusted range value
3319
     */
3320 21
    public function shrinkRangeToFit(string $range): string
3321
    {
3322 21
        $maxCol = $this->getHighestColumn();
3323 21
        $maxRow = $this->getHighestRow();
3324 21
        $maxCol = Coordinate::columnIndexFromString($maxCol);
3325
3326 21
        $rangeBlocks = explode(' ', $range);
3327 21
        foreach ($rangeBlocks as &$rangeSet) {
3328 21
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
3329
3330 21
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
3331
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
3332
            }
3333 21
            if ($rangeBoundaries[0][1] > $maxRow) {
3334
                $rangeBoundaries[0][1] = $maxRow;
3335
            }
3336 21
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
3337
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
3338
            }
3339 21
            if ($rangeBoundaries[1][1] > $maxRow) {
3340 4
                $rangeBoundaries[1][1] = $maxRow;
3341
            }
3342 21
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
3343
        }
3344 21
        unset($rangeSet);
3345
3346 21
        return implode(' ', $rangeBlocks);
3347
    }
3348
3349
    /**
3350
     * Get tab color.
3351
     */
3352 23
    public function getTabColor(): Color
3353
    {
3354 23
        if ($this->tabColor === null) {
3355 23
            $this->tabColor = new Color();
3356
        }
3357
3358 23
        return $this->tabColor;
3359
    }
3360
3361
    /**
3362
     * Reset tab color.
3363
     *
3364
     * @return $this
3365
     */
3366 1
    public function resetTabColor(): static
3367
    {
3368 1
        $this->tabColor = null;
3369
3370 1
        return $this;
3371
    }
3372
3373
    /**
3374
     * Tab color set?
3375
     */
3376 464
    public function isTabColorSet(): bool
3377
    {
3378 464
        return $this->tabColor !== null;
3379
    }
3380
3381
    /**
3382
     * Copy worksheet (!= clone!).
3383
     */
3384
    public function copy(): static
3385
    {
3386
        return clone $this;
3387
    }
3388
3389
    /**
3390
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3391
     *          exist in the collection for this row. false will be returned otherwise.
3392
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3393
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3394
     *                  cells, then the row will be considered empty.
3395
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3396
     *                  string value cells, then the row will be considered empty.
3397
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3398
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3399
     *                  will be considered empty.
3400
     *
3401
     * @param int $definitionOfEmptyFlags
3402
     *              Possible Flag Values are:
3403
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3404
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3405
     */
3406 9
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
3407
    {
3408
        try {
3409 9
            $iterator = new RowIterator($this, $rowId, $rowId);
3410 8
            $iterator->seek($rowId);
3411 8
            $row = $iterator->current();
3412 1
        } catch (Exception) {
3413 1
            return true;
3414
        }
3415
3416 8
        return $row->isEmpty($definitionOfEmptyFlags);
3417
    }
3418
3419
    /**
3420
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3421
     *          exist in the collection for this column. false will be returned otherwise.
3422
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3423
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3424
     *                  cells, then the column will be considered empty.
3425
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3426
     *                  string value cells, then the column will be considered empty.
3427
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3428
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3429
     *                  will be considered empty.
3430
     *
3431
     * @param int $definitionOfEmptyFlags
3432
     *              Possible Flag Values are:
3433
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3434
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3435
     */
3436 9
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
3437
    {
3438
        try {
3439 9
            $iterator = new ColumnIterator($this, $columnId, $columnId);
3440 8
            $iterator->seek($columnId);
3441 8
            $column = $iterator->current();
3442 1
        } catch (Exception) {
3443 1
            return true;
3444
        }
3445
3446 8
        return $column->isEmpty($definitionOfEmptyFlags);
3447
    }
3448
3449
    /**
3450
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3451
     */
3452 14
    public function __clone()
3453
    {
3454
        // @phpstan-ignore-next-line
3455 14
        foreach ($this as $key => $val) {
3456 14
            if ($key == 'parent') {
3457 14
                continue;
3458
            }
3459
3460 14
            if (is_object($val) || (is_array($val))) {
3461 14
                if ($key == 'cellCollection') {
3462 14
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
3463 14
                    $this->cellCollection = $newCollection;
3464 14
                } elseif ($key == 'drawingCollection') {
3465 14
                    $currentCollection = $this->drawingCollection;
3466 14
                    $this->drawingCollection = new ArrayObject();
3467 14
                    foreach ($currentCollection as $item) {
3468 4
                        $newDrawing = clone $item;
3469 4
                        $newDrawing->setWorksheet($this);
3470
                    }
3471 14
                } elseif ($key == 'tableCollection') {
3472 14
                    $currentCollection = $this->tableCollection;
3473 14
                    $this->tableCollection = new ArrayObject();
3474 14
                    foreach ($currentCollection as $item) {
3475 1
                        $newTable = clone $item;
3476 1
                        $newTable->setName($item->getName() . 'clone');
3477 1
                        $this->addTable($newTable);
3478
                    }
3479 14
                } elseif ($key == 'chartCollection') {
3480 14
                    $currentCollection = $this->chartCollection;
3481 14
                    $this->chartCollection = new ArrayObject();
3482 14
                    foreach ($currentCollection as $item) {
3483 5
                        $newChart = clone $item;
3484 5
                        $this->addChart($newChart);
3485
                    }
3486 14
                } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
3487 14
                    $newAutoFilter = clone $this->autoFilter;
3488 14
                    $this->autoFilter = $newAutoFilter;
3489 14
                    $this->autoFilter->setParent($this);
3490
                } else {
3491 14
                    $this->{$key} = unserialize(serialize($val));
3492
                }
3493
            }
3494
        }
3495 14
        $this->hash = spl_object_id($this);
3496
    }
3497
3498
    /**
3499
     * Define the code name of the sheet.
3500
     *
3501
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3502
     *                       silently space to underscore)
3503
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3504
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3505
     *
3506
     * @return $this
3507
     */
3508 10417
    public function setCodeName(string $codeName, bool $validate = true): static
3509
    {
3510
        // Is this a 'rename' or not?
3511 10417
        if ($this->getCodeName() == $codeName) {
3512
            return $this;
3513
        }
3514
3515 10417
        if ($validate) {
3516 10417
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
3517
3518
            // Syntax check
3519
            // throw an exception if not valid
3520 10417
            self::checkSheetCodeName($codeName);
3521
3522
            // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
3523
3524 10417
            if ($this->parent !== null) {
3525
                // Is there already such sheet name?
3526 10378
                if ($this->parent->sheetCodeNameExists($codeName)) {
3527
                    // Use name, but append with lowest possible integer
3528
3529 674
                    if (Shared\StringHelper::countCharacters($codeName) > 29) {
3530
                        $codeName = Shared\StringHelper::substring($codeName, 0, 29);
3531
                    }
3532 674
                    $i = 1;
3533 674
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
3534 275
                        ++$i;
3535 275
                        if ($i == 10) {
3536 2
                            if (Shared\StringHelper::countCharacters($codeName) > 28) {
3537
                                $codeName = Shared\StringHelper::substring($codeName, 0, 28);
3538
                            }
3539 275
                        } elseif ($i == 100) {
3540
                            if (Shared\StringHelper::countCharacters($codeName) > 27) {
3541
                                $codeName = Shared\StringHelper::substring($codeName, 0, 27);
3542
                            }
3543
                        }
3544
                    }
3545
3546 674
                    $codeName .= '_' . $i; // ok, we have a valid name
3547
                }
3548
            }
3549
        }
3550
3551 10417
        $this->codeName = $codeName;
3552
3553 10417
        return $this;
3554
    }
3555
3556
    /**
3557
     * Return the code name of the sheet.
3558
     */
3559 10417
    public function getCodeName(): ?string
3560
    {
3561 10417
        return $this->codeName;
3562
    }
3563
3564
    /**
3565
     * Sheet has a code name ?
3566
     */
3567 2
    public function hasCodeName(): bool
3568
    {
3569 2
        return $this->codeName !== null;
3570
    }
3571
3572 4
    public static function nameRequiresQuotes(string $sheetName): bool
3573
    {
3574 4
        return preg_match(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName) !== 1;
3575
    }
3576
3577 116
    public function isRowVisible(int $row): bool
3578
    {
3579 116
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
3580
    }
3581
3582
    /**
3583
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3584
     */
3585 1
    public function isCellLocked(string $coordinate): bool
3586
    {
3587 1
        if ($this->getProtection()->getsheet() !== true) {
3588 1
            return false;
3589
        }
3590 1
        if ($this->cellExists($coordinate)) {
3591 1
            return $this->getCell($coordinate)->isLocked();
3592
        }
3593 1
        $spreadsheet = $this->parent;
3594 1
        $xfIndex = $this->getXfIndex($coordinate);
3595 1
        if ($spreadsheet === null || $xfIndex === null) {
3596 1
            return true;
3597
        }
3598
3599
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
3600
    }
3601
3602
    /**
3603
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3604
     */
3605 1
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
3606
    {
3607 1
        if ($this->cellExists($coordinate)) {
3608 1
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
3609
        }
3610
3611
        // cell doesn't exist, therefore isn't a formula,
3612
        // therefore isn't hidden on formula bar.
3613 1
        return false;
3614
    }
3615
3616 1
    private function getXfIndex(string $coordinate): ?int
3617
    {
3618 1
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
3619 1
        $row = (int) $row;
3620 1
        $xfIndex = null;
3621 1
        if ($this->rowDimensionExists($row)) {
3622
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
3623
        }
3624 1
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
3625
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
3626
        }
3627
3628 1
        return $xfIndex;
3629
    }
3630
3631
    private string $backgroundImage = '';
3632
3633
    private string $backgroundMime = '';
3634
3635
    private string $backgroundExtension = '';
3636
3637 921
    public function getBackgroundImage(): string
3638
    {
3639 921
        return $this->backgroundImage;
3640
    }
3641
3642 367
    public function getBackgroundMime(): string
3643
    {
3644 367
        return $this->backgroundMime;
3645
    }
3646
3647 367
    public function getBackgroundExtension(): string
3648
    {
3649 367
        return $this->backgroundExtension;
3650
    }
3651
3652
    /**
3653
     * Set background image.
3654
     * Used on read/write for Xlsx.
3655
     * Used on write for Html.
3656
     *
3657
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3658
     */
3659 4
    public function setBackgroundImage(string $backgroundImage): self
3660
    {
3661 4
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
3662 4
        $mime = $imageArray['mime'];
3663 4
        if ($mime !== '') {
3664 3
            $extension = explode('/', $mime);
3665 3
            $extension = $extension[1];
3666 3
            $this->backgroundImage = $backgroundImage;
3667 3
            $this->backgroundMime = $mime;
3668 3
            $this->backgroundExtension = $extension;
3669
        }
3670
3671 4
        return $this;
3672
    }
3673
3674
    /**
3675
     * Copy cells, adjusting relative cell references in formulas.
3676
     * Acts similarly to Excel "fill handle" feature.
3677
     *
3678
     * @param string $fromCell Single source cell, e.g. C3
3679
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3680
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3681
     */
3682 1
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
3683
    {
3684 1
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
3685 1
        $valueString = $this->getCell($fromCell)->getValueString();
3686 1
        $style = $this->getStyle($fromCell)->exportArray();
3687 1
        $fromIndexes = Coordinate::indexesFromString($fromCell);
3688 1
        $referenceHelper = ReferenceHelper::getInstance();
3689 1
        foreach ($toArray as $destination) {
3690 1
            if ($destination !== $fromCell) {
3691 1
                $toIndexes = Coordinate::indexesFromString($destination);
3692 1
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
3693 1
                if ($copyStyle) {
3694 1
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
3695
                }
3696
            }
3697
        }
3698
    }
3699
3700 1067
    public function calculateArrays(bool $preCalculateFormulas = true): void
3701
    {
3702 1067
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
3703 41
            $keys = $this->cellCollection->getCoordinates();
3704 41
            foreach ($keys as $key) {
3705 41
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
3706 41
                    if (preg_match(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValue()) !== 1) {
3707 41
                        $this->getCell($key)->getCalculatedValue();
3708
                    }
3709
                }
3710
            }
3711
        }
3712
    }
3713
3714 2
    public function isCellInSpillRange(string $coordinate): bool
3715
    {
3716 2
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
3717 1
            return false;
3718
        }
3719 1
        $this->calculateArrays();
3720 1
        $keys = $this->cellCollection->getCoordinates();
3721 1
        foreach ($keys as $key) {
3722 1
            $attributes = $this->getCell($key)->getFormulaAttributes();
3723 1
            if (isset($attributes['ref'])) {
3724 1
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
3725
                    // false for first cell in range, true otherwise
3726 1
                    return $coordinate !== $key;
3727
                }
3728
            }
3729
        }
3730
3731 1
        return false;
3732
    }
3733
3734 2
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
3735
    {
3736 2
        $spreadsheet = $this->parent;
3737 2
        if ($spreadsheet === null) {
3738 1
            return false;
3739
        }
3740 1
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
3741 1
        $originalSelected = $this->selectedCells;
3742 1
        $this->getStyle($coordinate)->applyFromArray($styleArray);
3743 1
        $this->setSelectedCells($originalSelected);
3744 1
        if ($activeSheetIndex >= 0) {
3745 1
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
3746
        }
3747
3748 1
        return true;
3749
    }
3750
}
3751