Passed
Pull Request — master (#4207)
by Owen
13:19
created

Worksheet::dataValidationExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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