Passed
Pull Request — master (#4370)
by Owen
12:31
created

Worksheet::getBreaks()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

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