Passed
Pull Request — master (#4240)
by Owen
13:49
created

Worksheet::getColumnBreaks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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