Failed Conditions
Pull Request — master (#3962)
by Owen
11:35
created

Worksheet::rangeToArrayYieldRows()   D

Complexity

Conditions 19
Paths 4

Size

Total Lines 68
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 19

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 68
ccs 39
cts 39
cp 1
rs 4.5166
c 0
b 0
f 0
cc 19
nc 4
nop 7
crap 19

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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