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

Worksheet::getDataValidation()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7

Importance

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