Failed Conditions
Pull Request — master (#4328)
by Owen
15:26 queued 04:43
created

Worksheet::getRowIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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