Failed Conditions
Pull Request — master (#4314)
by Owen
11:26
created

Worksheet::getConditionalStyles()   B

Complexity

Conditions 11
Paths 21

Size

Total Lines 40
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 11

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 40
ccs 19
cts 19
cp 1
rs 7.3166
cc 11
nc 21
nop 2
crap 11

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

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