• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 17606548582

10 Sep 2025 07:30AM UTC coverage: 95.299% (+0.001%) from 95.298%
17606548582

Pull #4639

github

web-flow
Merge 00191100b into 109b2b282
Pull Request #4639: Deprecate Worksheet::getHashInt and Spreadsheet::getId

5 of 6 new or added lines in 5 files covered. (83.33%)

1 existing line in 1 file now uncovered.

40303 of 42291 relevant lines covered (95.3%)

347.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.93
/src/PhpSpreadsheet/Worksheet/Worksheet.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4

5
use ArrayObject;
6
use Composer\Pcre\Preg;
7
use Generator;
8
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
9
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
10
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
11
use PhpOffice\PhpSpreadsheet\Cell\Cell;
12
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
13
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
14
use PhpOffice\PhpSpreadsheet\Cell\DataType;
15
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
16
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
17
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
18
use PhpOffice\PhpSpreadsheet\Chart\Chart;
19
use PhpOffice\PhpSpreadsheet\Collection\Cells;
20
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
21
use PhpOffice\PhpSpreadsheet\Comment;
22
use PhpOffice\PhpSpreadsheet\DefinedName;
23
use PhpOffice\PhpSpreadsheet\Exception;
24
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
25
use PhpOffice\PhpSpreadsheet\RichText\RichText;
26
use PhpOffice\PhpSpreadsheet\Shared;
27
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
28
use PhpOffice\PhpSpreadsheet\Spreadsheet;
29
use PhpOffice\PhpSpreadsheet\Style\Alignment;
30
use PhpOffice\PhpSpreadsheet\Style\Color;
31
use PhpOffice\PhpSpreadsheet\Style\Conditional;
32
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
33
use PhpOffice\PhpSpreadsheet\Style\Protection as StyleProtection;
34
use PhpOffice\PhpSpreadsheet\Style\Style;
35

36
class Worksheet
37
{
38
    // Break types
39
    public const BREAK_NONE = 0;
40
    public const BREAK_ROW = 1;
41
    public const BREAK_COLUMN = 2;
42
    // Maximum column for row break
43
    public const BREAK_ROW_MAX_COLUMN = 16383;
44

45
    // Sheet state
46
    public const SHEETSTATE_VISIBLE = 'visible';
47
    public const SHEETSTATE_HIDDEN = 'hidden';
48
    public const SHEETSTATE_VERYHIDDEN = 'veryHidden';
49

50
    public const MERGE_CELL_CONTENT_EMPTY = 'empty';
51
    public const MERGE_CELL_CONTENT_HIDE = 'hide';
52
    public const MERGE_CELL_CONTENT_MERGE = 'merge';
53

54
    public const FUNCTION_LIKE_GROUPBY = '/\b(groupby|_xleta)\b/i'; // weird new syntax
55

56
    protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui';
57

58
    /**
59
     * Maximum 31 characters allowed for sheet title.
60
     *
61
     * @var int
62
     */
63
    const SHEET_TITLE_MAXIMUM_LENGTH = 31;
64

65
    /**
66
     * Invalid characters in sheet title.
67
     */
68
    private const INVALID_CHARACTERS = ['*', ':', '/', '\\', '?', '[', ']'];
69

70
    /**
71
     * Parent spreadsheet.
72
     */
73
    private ?Spreadsheet $parent = null;
74

75
    /**
76
     * Collection of cells.
77
     */
78
    private Cells $cellCollection;
79

80
    /**
81
     * Collection of row dimensions.
82
     *
83
     * @var RowDimension[]
84
     */
85
    private array $rowDimensions = [];
86

87
    /**
88
     * Default row dimension.
89
     */
90
    private RowDimension $defaultRowDimension;
91

92
    /**
93
     * Collection of column dimensions.
94
     *
95
     * @var ColumnDimension[]
96
     */
97
    private array $columnDimensions = [];
98

99
    /**
100
     * Default column dimension.
101
     */
102
    private ColumnDimension $defaultColumnDimension;
103

104
    /**
105
     * Collection of drawings.
106
     *
107
     * @var ArrayObject<int, BaseDrawing>
108
     */
109
    private ArrayObject $drawingCollection;
110

111
    /**
112
     * Collection of Chart objects.
113
     *
114
     * @var ArrayObject<int, Chart>
115
     */
116
    private ArrayObject $chartCollection;
117

118
    /**
119
     * Collection of Table objects.
120
     *
121
     * @var ArrayObject<int, Table>
122
     */
123
    private ArrayObject $tableCollection;
124

125
    /**
126
     * Worksheet title.
127
     */
128
    private string $title = '';
129

130
    /**
131
     * Sheet state.
132
     */
133
    private string $sheetState;
134

135
    /**
136
     * Page setup.
137
     */
138
    private PageSetup $pageSetup;
139

140
    /**
141
     * Page margins.
142
     */
143
    private PageMargins $pageMargins;
144

145
    /**
146
     * Page header/footer.
147
     */
148
    private HeaderFooter $headerFooter;
149

150
    /**
151
     * Sheet view.
152
     */
153
    private SheetView $sheetView;
154

155
    /**
156
     * Protection.
157
     */
158
    private Protection $protection;
159

160
    /**
161
     * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
162
     *
163
     * @var Conditional[][]
164
     */
165
    private array $conditionalStylesCollection = [];
166

167
    /**
168
     * Collection of row breaks.
169
     *
170
     * @var PageBreak[]
171
     */
172
    private array $rowBreaks = [];
173

174
    /**
175
     * Collection of column breaks.
176
     *
177
     * @var PageBreak[]
178
     */
179
    private array $columnBreaks = [];
180

181
    /**
182
     * Collection of merged cell ranges.
183
     *
184
     * @var string[]
185
     */
186
    private array $mergeCells = [];
187

188
    /**
189
     * Collection of protected cell ranges.
190
     *
191
     * @var ProtectedRange[]
192
     */
193
    private array $protectedCells = [];
194

195
    /**
196
     * Autofilter Range and selection.
197
     */
198
    private AutoFilter $autoFilter;
199

200
    /**
201
     * Freeze pane.
202
     */
203
    private ?string $freezePane = null;
204

205
    /**
206
     * Default position of the right bottom pane.
207
     */
208
    private ?string $topLeftCell = null;
209

210
    private string $paneTopLeftCell = '';
211

212
    private string $activePane = '';
213

214
    private int $xSplit = 0;
215

216
    private int $ySplit = 0;
217

218
    private string $paneState = '';
219

220
    /**
221
     * Properties of the 4 panes.
222
     *
223
     * @var (null|Pane)[]
224
     */
225
    private array $panes = [
226
        'bottomRight' => null,
227
        'bottomLeft' => null,
228
        'topRight' => null,
229
        'topLeft' => null,
230
    ];
231

232
    /**
233
     * Show gridlines?
234
     */
235
    private bool $showGridlines = true;
236

237
    /**
238
     * Print gridlines?
239
     */
240
    private bool $printGridlines = false;
241

242
    /**
243
     * Show row and column headers?
244
     */
245
    private bool $showRowColHeaders = true;
246

247
    /**
248
     * Show summary below? (Row/Column outline).
249
     */
250
    private bool $showSummaryBelow = true;
251

252
    /**
253
     * Show summary right? (Row/Column outline).
254
     */
255
    private bool $showSummaryRight = true;
256

257
    /**
258
     * Collection of comments.
259
     *
260
     * @var Comment[]
261
     */
262
    private array $comments = [];
263

264
    /**
265
     * Active cell. (Only one!).
266
     */
267
    private string $activeCell = 'A1';
268

269
    /**
270
     * Selected cells.
271
     */
272
    private string $selectedCells = 'A1';
273

274
    /**
275
     * Cached highest column.
276
     */
277
    private int $cachedHighestColumn = 1;
278

279
    /**
280
     * Cached highest row.
281
     */
282
    private int $cachedHighestRow = 1;
283

284
    /**
285
     * Right-to-left?
286
     */
287
    private bool $rightToLeft = false;
288

289
    /**
290
     * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
291
     *
292
     * @var Hyperlink[]
293
     */
294
    private array $hyperlinkCollection = [];
295

296
    /**
297
     * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
298
     * Index can include ranges, and multiple cells/ranges.
299
     *
300
     * @var DataValidation[]
301
     */
302
    private array $dataValidationCollection = [];
303

304
    /**
305
     * Tab color.
306
     */
307
    private ?Color $tabColor = null;
308

309
    /**
310
     * CodeName.
311
     */
312
    private ?string $codeName = null;
313

314
    /**
315
     * Create a new worksheet.
316
     */
317
    public function __construct(?Spreadsheet $parent = null, string $title = 'Worksheet')
318
    {
319
        // Set parent and title
320
        $this->parent = $parent;
10,737✔
321
        $this->setTitle($title, false);
10,737✔
322
        // setTitle can change $pTitle
323
        $this->setCodeName($this->getTitle());
10,737✔
324
        $this->setSheetState(self::SHEETSTATE_VISIBLE);
10,737✔
325

326
        $this->cellCollection = CellsFactory::getInstance($this);
10,737✔
327
        // Set page setup
328
        $this->pageSetup = new PageSetup();
10,737✔
329
        // Set page margins
330
        $this->pageMargins = new PageMargins();
10,737✔
331
        // Set page header/footer
332
        $this->headerFooter = new HeaderFooter();
10,737✔
333
        // Set sheet view
334
        $this->sheetView = new SheetView();
10,737✔
335
        // Drawing collection
336
        $this->drawingCollection = new ArrayObject();
10,737✔
337
        // Chart collection
338
        $this->chartCollection = new ArrayObject();
10,737✔
339
        // Protection
340
        $this->protection = new Protection();
10,737✔
341
        // Default row dimension
342
        $this->defaultRowDimension = new RowDimension(null);
10,737✔
343
        // Default column dimension
344
        $this->defaultColumnDimension = new ColumnDimension(null);
10,737✔
345
        // AutoFilter
346
        $this->autoFilter = new AutoFilter('', $this);
10,737✔
347
        // Table collection
348
        $this->tableCollection = new ArrayObject();
10,737✔
349
    }
350

351
    /**
352
     * Disconnect all cells from this Worksheet object,
353
     * typically so that the worksheet object can be unset.
354
     */
355
    public function disconnectCells(): void
356
    {
357
        if (isset($this->cellCollection)) { //* @phpstan-ignore-line
9,777✔
358
            $this->cellCollection->unsetWorksheetCells();
9,776✔
359
            unset($this->cellCollection);
9,776✔
360
        }
361
        //    detach ourself from the workbook, so that it can then delete this worksheet successfully
362
        $this->parent = null;
9,777✔
363
    }
364

365
    /**
366
     * Code to execute when this worksheet is unset().
367
     */
368
    public function __destruct()
369
    {
370
        Calculation::getInstanceOrNull($this->parent)
133✔
371
            ?->clearCalculationCacheForWorksheet($this->title);
133✔
372

373
        $this->disconnectCells();
133✔
374
        unset($this->rowDimensions, $this->columnDimensions, $this->tableCollection, $this->drawingCollection, $this->chartCollection, $this->autoFilter);
133✔
375
    }
376

377
    /**
378
     * Return the cell collection.
379
     */
380
    public function getCellCollection(): Cells
381
    {
382
        return $this->cellCollection;
10,336✔
383
    }
384

385
    /**
386
     * Get array of invalid characters for sheet title.
387
     *
388
     * @return string[]
389
     */
390
    public static function getInvalidCharacters(): array
391
    {
392
        return self::INVALID_CHARACTERS;
1✔
393
    }
394

395
    /**
396
     * Check sheet code name for valid Excel syntax.
397
     *
398
     * @param string $sheetCodeName The string to check
399
     *
400
     * @return string The valid string
401
     */
402
    private static function checkSheetCodeName(string $sheetCodeName): string
403
    {
404
        $charCount = StringHelper::countCharacters($sheetCodeName);
10,737✔
405
        if ($charCount == 0) {
10,737✔
406
            throw new Exception('Sheet code name cannot be empty.');
1✔
407
        }
408
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ] and  first and last characters cannot be a "'"
409
        if (
410
            (str_replace(self::INVALID_CHARACTERS, '', $sheetCodeName) !== $sheetCodeName)
10,737✔
411
            || (StringHelper::substring($sheetCodeName, -1, 1) == '\'')
10,737✔
412
            || (StringHelper::substring($sheetCodeName, 0, 1) == '\'')
10,737✔
413
        ) {
414
            throw new Exception('Invalid character found in sheet code name');
1✔
415
        }
416

417
        // Enforce maximum characters allowed for sheet title
418
        if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
10,737✔
419
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
1✔
420
        }
421

422
        return $sheetCodeName;
10,737✔
423
    }
424

425
    /**
426
     * Check sheet title for valid Excel syntax.
427
     *
428
     * @param string $sheetTitle The string to check
429
     *
430
     * @return string The valid string
431
     */
432
    private static function checkSheetTitle(string $sheetTitle): string
433
    {
434
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ]
435
        if (str_replace(self::INVALID_CHARACTERS, '', $sheetTitle) !== $sheetTitle) {
10,737✔
436
            throw new Exception('Invalid character found in sheet title');
2✔
437
        }
438

439
        // Enforce maximum characters allowed for sheet title
440
        if (StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
10,737✔
441
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
3✔
442
        }
443

444
        return $sheetTitle;
10,737✔
445
    }
446

447
    /**
448
     * Get a sorted list of all cell coordinates currently held in the collection by row and column.
449
     *
450
     * @param bool $sorted Also sort the cell collection?
451
     *
452
     * @return string[]
453
     */
454
    public function getCoordinates(bool $sorted = true): array
455
    {
456
        if (!isset($this->cellCollection)) { //* @phpstan-ignore-line
1,511✔
457
            return [];
1✔
458
        }
459

460
        if ($sorted) {
1,511✔
461
            return $this->cellCollection->getSortedCoordinates();
576✔
462
        }
463

464
        return $this->cellCollection->getCoordinates();
1,370✔
465
    }
466

467
    /**
468
     * Get collection of row dimensions.
469
     *
470
     * @return RowDimension[]
471
     */
472
    public function getRowDimensions(): array
473
    {
474
        return $this->rowDimensions;
1,225✔
475
    }
476

477
    /**
478
     * Get default row dimension.
479
     */
480
    public function getDefaultRowDimension(): RowDimension
481
    {
482
        return $this->defaultRowDimension;
1,143✔
483
    }
484

485
    /**
486
     * Get collection of column dimensions.
487
     *
488
     * @return ColumnDimension[]
489
     */
490
    public function getColumnDimensions(): array
491
    {
492
        /** @var callable $callable */
493
        $callable = [self::class, 'columnDimensionCompare'];
1,231✔
494
        uasort($this->columnDimensions, $callable);
1,231✔
495

496
        return $this->columnDimensions;
1,231✔
497
    }
498

499
    private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int
500
    {
501
        return $a->getColumnNumeric() - $b->getColumnNumeric();
98✔
502
    }
503

504
    /**
505
     * Get default column dimension.
506
     */
507
    public function getDefaultColumnDimension(): ColumnDimension
508
    {
509
        return $this->defaultColumnDimension;
596✔
510
    }
511

512
    /**
513
     * Get collection of drawings.
514
     *
515
     * @return ArrayObject<int, BaseDrawing>
516
     */
517
    public function getDrawingCollection(): ArrayObject
518
    {
519
        return $this->drawingCollection;
1,205✔
520
    }
521

522
    /**
523
     * Get collection of charts.
524
     *
525
     * @return ArrayObject<int, Chart>
526
     */
527
    public function getChartCollection(): ArrayObject
528
    {
529
        return $this->chartCollection;
100✔
530
    }
531

532
    public function addChart(Chart $chart): Chart
533
    {
534
        $chart->setWorksheet($this);
106✔
535
        $this->chartCollection[] = $chart;
106✔
536

537
        return $chart;
106✔
538
    }
539

540
    /**
541
     * Return the count of charts on this worksheet.
542
     *
543
     * @return int The number of charts
544
     */
545
    public function getChartCount(): int
546
    {
547
        return count($this->chartCollection);
83✔
548
    }
549

550
    /**
551
     * Get a chart by its index position.
552
     *
553
     * @param ?string $index Chart index position
554
     *
555
     * @return Chart|false
556
     */
557
    public function getChartByIndex(?string $index)
558
    {
559
        $chartCount = count($this->chartCollection);
78✔
560
        if ($chartCount == 0) {
78✔
561
            return false;
×
562
        }
563
        if ($index === null) {
78✔
564
            $index = --$chartCount;
×
565
        }
566
        if (!isset($this->chartCollection[$index])) {
78✔
567
            return false;
×
568
        }
569

570
        return $this->chartCollection[$index];
78✔
571
    }
572

573
    /**
574
     * Return an array of the names of charts on this worksheet.
575
     *
576
     * @return string[] The names of charts
577
     */
578
    public function getChartNames(): array
579
    {
580
        $chartNames = [];
5✔
581
        foreach ($this->chartCollection as $chart) {
5✔
582
            $chartNames[] = $chart->getName();
5✔
583
        }
584

585
        return $chartNames;
5✔
586
    }
587

588
    /**
589
     * Get a chart by name.
590
     *
591
     * @param string $chartName Chart name
592
     *
593
     * @return Chart|false
594
     */
595
    public function getChartByName(string $chartName)
596
    {
597
        foreach ($this->chartCollection as $index => $chart) {
6✔
598
            if ($chart->getName() == $chartName) {
6✔
599
                return $chart;
6✔
600
            }
601
        }
602

603
        return false;
1✔
604
    }
605

606
    public function getChartByNameOrThrow(string $chartName): Chart
607
    {
608
        $chart = $this->getChartByName($chartName);
6✔
609
        if ($chart !== false) {
6✔
610
            return $chart;
6✔
611
        }
612

613
        throw new Exception("Sheet does not have a chart named $chartName.");
1✔
614
    }
615

616
    /**
617
     * Refresh column dimensions.
618
     *
619
     * @return $this
620
     */
621
    public function refreshColumnDimensions(): static
622
    {
623
        $newColumnDimensions = [];
25✔
624
        foreach ($this->getColumnDimensions() as $objColumnDimension) {
25✔
625
            $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
25✔
626
        }
627

628
        $this->columnDimensions = $newColumnDimensions;
25✔
629

630
        return $this;
25✔
631
    }
632

633
    /**
634
     * Refresh row dimensions.
635
     *
636
     * @return $this
637
     */
638
    public function refreshRowDimensions(): static
639
    {
640
        $newRowDimensions = [];
7✔
641
        foreach ($this->getRowDimensions() as $objRowDimension) {
7✔
642
            $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
7✔
643
        }
644

645
        $this->rowDimensions = $newRowDimensions;
7✔
646

647
        return $this;
7✔
648
    }
649

650
    /**
651
     * Calculate worksheet dimension.
652
     *
653
     * @return string String containing the dimension of this worksheet
654
     */
655
    public function calculateWorksheetDimension(): string
656
    {
657
        // Return
658
        return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
484✔
659
    }
660

661
    /**
662
     * Calculate worksheet data dimension.
663
     *
664
     * @return string String containing the dimension of this worksheet that actually contain data
665
     */
666
    public function calculateWorksheetDataDimension(): string
667
    {
668
        // Return
669
        return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
559✔
670
    }
671

672
    /**
673
     * Calculate widths for auto-size columns.
674
     *
675
     * @return $this
676
     */
677
    public function calculateColumnWidths(): static
678
    {
679
        $activeSheet = $this->getParent()?->getActiveSheetIndex();
790✔
680
        $selectedCells = $this->selectedCells;
790✔
681
        // initialize $autoSizes array
682
        $autoSizes = [];
790✔
683
        foreach ($this->getColumnDimensions() as $colDimension) {
790✔
684
            if ($colDimension->getAutoSize()) {
160✔
685
                $autoSizes[$colDimension->getColumnIndex()] = -1;
65✔
686
            }
687
        }
688

689
        // There is only something to do if there are some auto-size columns
690
        if (!empty($autoSizes)) {
790✔
691
            $holdActivePane = $this->activePane;
65✔
692
            // build list of cells references that participate in a merge
693
            $isMergeCell = [];
65✔
694
            foreach ($this->getMergeCells() as $cells) {
65✔
695
                foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
16✔
696
                    $isMergeCell[$cellReference] = true;
16✔
697
                }
698
            }
699

700
            $autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges();
65✔
701

702
            // loop through all cells in the worksheet
703
            foreach ($this->getCoordinates(false) as $coordinate) {
65✔
704
                $cell = $this->getCellOrNull($coordinate);
65✔
705

706
                if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
65✔
707
                    //Determine if cell is in merge range
708
                    $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
65✔
709

710
                    //By default merged cells should be ignored
711
                    $isMergedButProceed = false;
65✔
712

713
                    //The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide)
714
                    if ($isMerged && $cell->isMergeRangeValueCell()) {
65✔
715
                        $range = (string) $cell->getMergeRange();
×
716
                        $rangeBoundaries = Coordinate::rangeDimension($range);
×
717
                        if ($rangeBoundaries[0] === 1) {
×
718
                            $isMergedButProceed = true;
×
719
                        }
720
                    }
721

722
                    // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range
723
                    if (!$isMerged || $isMergedButProceed) {
65✔
724
                        // Determine if we need to make an adjustment for the first row in an AutoFilter range that
725
                        //    has a column filter dropdown
726
                        $filterAdjustment = false;
65✔
727
                        if (!empty($autoFilterIndentRanges)) {
65✔
728
                            foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) {
4✔
729
                                /** @var string $autoFilterFirstRowRange */
730
                                if ($cell->isInRange($autoFilterFirstRowRange)) {
4✔
731
                                    $filterAdjustment = true;
4✔
732

733
                                    break;
4✔
734
                                }
735
                            }
736
                        }
737

738
                        $indentAdjustment = $cell->getStyle()->getAlignment()->getIndent();
65✔
739
                        $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER);
65✔
740

741
                        // Calculated value
742
                        // To formatted string
743
                        $cellValue = NumberFormat::toFormattedString(
65✔
744
                            $cell->getCalculatedValueString(),
65✔
745
                            (string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
65✔
746
                                ->getNumberFormat()->getFormatCode(true)
65✔
747
                        );
65✔
748

749
                        if ($cellValue !== '') {
65✔
750
                            $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
65✔
751
                                $autoSizes[$this->cellCollection->getCurrentColumn()],
65✔
752
                                round(
65✔
753
                                    Shared\Font::calculateColumnWidth(
65✔
754
                                        $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(),
65✔
755
                                        $cellValue,
65✔
756
                                        (int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
65✔
757
                                            ->getAlignment()->getTextRotation(),
65✔
758
                                        $this->getParentOrThrow()->getDefaultStyle()->getFont(),
65✔
759
                                        $filterAdjustment,
65✔
760
                                        $indentAdjustment
65✔
761
                                    ),
65✔
762
                                    3
65✔
763
                                )
65✔
764
                            );
65✔
765
                        }
766
                    }
767
                }
768
            }
769

770
            // adjust column widths
771
            foreach ($autoSizes as $columnIndex => $width) {
65✔
772
                if ($width == -1) {
65✔
773
                    $width = $this->getDefaultColumnDimension()->getWidth();
×
774
                }
775
                $this->getColumnDimension($columnIndex)->setWidth($width);
65✔
776
            }
777
            $this->activePane = $holdActivePane;
65✔
778
        }
779
        if ($activeSheet !== null && $activeSheet >= 0) {
790✔
780
            $this->getParent()?->setActiveSheetIndex($activeSheet);
790✔
781
        }
782
        $this->setSelectedCells($selectedCells);
790✔
783

784
        return $this;
790✔
785
    }
786

787
    /**
788
     * Get parent or null.
789
     */
790
    public function getParent(): ?Spreadsheet
791
    {
792
        return $this->parent;
10,346✔
793
    }
794

795
    /**
796
     * Get parent, throw exception if null.
797
     */
798
    public function getParentOrThrow(): Spreadsheet
799
    {
800
        if ($this->parent !== null) {
10,417✔
801
            return $this->parent;
10,416✔
802
        }
803

804
        throw new Exception('Sheet does not have a parent.');
1✔
805
    }
806

807
    /**
808
     * Re-bind parent.
809
     *
810
     * @return $this
811
     */
812
    public function rebindParent(Spreadsheet $parent): static
813
    {
814
        if ($this->parent !== null) {
54✔
815
            $definedNames = $this->parent->getDefinedNames();
4✔
816
            foreach ($definedNames as $definedName) {
4✔
817
                $parent->addDefinedName($definedName);
×
818
            }
819

820
            $this->parent->removeSheetByIndex(
4✔
821
                $this->parent->getIndex($this)
4✔
822
            );
4✔
823
        }
824
        $this->parent = $parent;
54✔
825

826
        return $this;
54✔
827
    }
828

829
    public function setParent(Spreadsheet $parent): self
830
    {
831
        $this->parent = $parent;
5✔
832

833
        return $this;
5✔
834
    }
835

836
    /**
837
     * Get title.
838
     */
839
    public function getTitle(): string
840
    {
841
        return $this->title;
10,738✔
842
    }
843

844
    /**
845
     * Set title.
846
     *
847
     * @param string $title String containing the dimension of this worksheet
848
     * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
849
     *            be updated to reflect the new sheet name.
850
     *          This should be left as the default true, unless you are
851
     *          certain that no formula cells on any worksheet contain
852
     *          references to this worksheet
853
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
854
     *                       at parse time (by Readers), where titles can be assumed to be valid.
855
     *
856
     * @return $this
857
     */
858
    public function setTitle(string $title, bool $updateFormulaCellReferences = true, bool $validate = true): static
859
    {
860
        // Is this a 'rename' or not?
861
        if ($this->getTitle() == $title) {
10,737✔
862
            return $this;
299✔
863
        }
864

865
        // Old title
866
        $oldTitle = $this->getTitle();
10,737✔
867

868
        if ($validate) {
10,737✔
869
            // Syntax check
870
            self::checkSheetTitle($title);
10,737✔
871

872
            if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
10,737✔
873
                // Is there already such sheet name?
874
                if ($this->parent->sheetNameExists($title)) {
814✔
875
                    // Use name, but append with lowest possible integer
876

877
                    if (StringHelper::countCharacters($title) > 29) {
2✔
878
                        $title = StringHelper::substring($title, 0, 29);
×
879
                    }
880
                    $i = 1;
2✔
881
                    while ($this->parent->sheetNameExists($title . ' ' . $i)) {
2✔
882
                        ++$i;
1✔
883
                        if ($i == 10) {
1✔
884
                            if (StringHelper::countCharacters($title) > 28) {
×
885
                                $title = StringHelper::substring($title, 0, 28);
×
886
                            }
887
                        } elseif ($i == 100) {
1✔
888
                            if (StringHelper::countCharacters($title) > 27) {
×
889
                                $title = StringHelper::substring($title, 0, 27);
×
890
                            }
891
                        }
892
                    }
893

894
                    $title .= " $i";
2✔
895
                }
896
            }
897
        }
898

899
        // Set title
900
        $this->title = $title;
10,737✔
901

902
        if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
10,737✔
903
            // New title
904
            $newTitle = $this->getTitle();
1,435✔
905
            $this->parent->getCalculationEngine()
1,435✔
906
                ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
1,435✔
907
            if ($updateFormulaCellReferences) {
1,435✔
908
                ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle);
814✔
909
            }
910
        }
911

912
        return $this;
10,737✔
913
    }
914

915
    /**
916
     * Get sheet state.
917
     *
918
     * @return string Sheet state (visible, hidden, veryHidden)
919
     */
920
    public function getSheetState(): string
921
    {
922
        return $this->sheetState;
515✔
923
    }
924

925
    /**
926
     * Set sheet state.
927
     *
928
     * @param string $value Sheet state (visible, hidden, veryHidden)
929
     *
930
     * @return $this
931
     */
932
    public function setSheetState(string $value): static
933
    {
934
        $this->sheetState = $value;
10,737✔
935

936
        return $this;
10,737✔
937
    }
938

939
    /**
940
     * Get page setup.
941
     */
942
    public function getPageSetup(): PageSetup
943
    {
944
        return $this->pageSetup;
1,624✔
945
    }
946

947
    /**
948
     * Set page setup.
949
     *
950
     * @return $this
951
     */
952
    public function setPageSetup(PageSetup $pageSetup): static
953
    {
954
        $this->pageSetup = $pageSetup;
1✔
955

956
        return $this;
1✔
957
    }
958

959
    /**
960
     * Get page margins.
961
     */
962
    public function getPageMargins(): PageMargins
963
    {
964
        return $this->pageMargins;
1,620✔
965
    }
966

967
    /**
968
     * Set page margins.
969
     *
970
     * @return $this
971
     */
972
    public function setPageMargins(PageMargins $pageMargins): static
973
    {
974
        $this->pageMargins = $pageMargins;
1✔
975

976
        return $this;
1✔
977
    }
978

979
    /**
980
     * Get page header/footer.
981
     */
982
    public function getHeaderFooter(): HeaderFooter
983
    {
984
        return $this->headerFooter;
589✔
985
    }
986

987
    /**
988
     * Set page header/footer.
989
     *
990
     * @return $this
991
     */
992
    public function setHeaderFooter(HeaderFooter $headerFooter): static
993
    {
994
        $this->headerFooter = $headerFooter;
1✔
995

996
        return $this;
1✔
997
    }
998

999
    /**
1000
     * Get sheet view.
1001
     */
1002
    public function getSheetView(): SheetView
1003
    {
1004
        return $this->sheetView;
619✔
1005
    }
1006

1007
    /**
1008
     * Set sheet view.
1009
     *
1010
     * @return $this
1011
     */
1012
    public function setSheetView(SheetView $sheetView): static
1013
    {
1014
        $this->sheetView = $sheetView;
1✔
1015

1016
        return $this;
1✔
1017
    }
1018

1019
    /**
1020
     * Get Protection.
1021
     */
1022
    public function getProtection(): Protection
1023
    {
1024
        return $this->protection;
642✔
1025
    }
1026

1027
    /**
1028
     * Set Protection.
1029
     *
1030
     * @return $this
1031
     */
1032
    public function setProtection(Protection $protection): static
1033
    {
1034
        $this->protection = $protection;
1✔
1035

1036
        return $this;
1✔
1037
    }
1038

1039
    /**
1040
     * Get highest worksheet column.
1041
     *
1042
     * @param null|int|string $row Return the data highest column for the specified row,
1043
     *                                     or the highest column of any row if no row number is passed
1044
     *
1045
     * @return string Highest column name
1046
     */
1047
    public function getHighestColumn($row = null): string
1048
    {
1049
        if ($row === null) {
1,525✔
1050
            return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
1,524✔
1051
        }
1052

1053
        return $this->getHighestDataColumn($row);
1✔
1054
    }
1055

1056
    /**
1057
     * Get highest worksheet column that contains data.
1058
     *
1059
     * @param null|int|string $row Return the highest data column for the specified row,
1060
     *                                     or the highest data column of any row if no row number is passed
1061
     *
1062
     * @return string Highest column name that contains data
1063
     */
1064
    public function getHighestDataColumn($row = null): string
1065
    {
1066
        return $this->cellCollection->getHighestColumn($row);
724✔
1067
    }
1068

1069
    /**
1070
     * Get highest worksheet row.
1071
     *
1072
     * @param null|string $column Return the highest data row for the specified column,
1073
     *                                     or the highest row of any column if no column letter is passed
1074
     *
1075
     * @return int Highest row number
1076
     */
1077
    public function getHighestRow(?string $column = null): int
1078
    {
1079
        if ($column === null) {
1,005✔
1080
            return $this->cachedHighestRow;
1,004✔
1081
        }
1082

1083
        return $this->getHighestDataRow($column);
1✔
1084
    }
1085

1086
    /**
1087
     * Get highest worksheet row that contains data.
1088
     *
1089
     * @param null|string $column Return the highest data row for the specified column,
1090
     *                                     or the highest data row of any column if no column letter is passed
1091
     *
1092
     * @return int Highest row number that contains data
1093
     */
1094
    public function getHighestDataRow(?string $column = null): int
1095
    {
1096
        return $this->cellCollection->getHighestRow($column);
725✔
1097
    }
1098

1099
    /**
1100
     * Get highest worksheet column and highest row that have cell records.
1101
     *
1102
     * @return array{row: int, column: string} Highest column name and highest row number
1103
     */
1104
    public function getHighestRowAndColumn(): array
1105
    {
1106
        return $this->cellCollection->getHighestRowAndColumn();
1✔
1107
    }
1108

1109
    /**
1110
     * Set a cell value.
1111
     *
1112
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1113
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1114
     * @param mixed $value Value for the cell
1115
     * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
1116
     *
1117
     * @return $this
1118
     */
1119
    public function setCellValue(CellAddress|string|array $coordinate, mixed $value, ?IValueBinder $binder = null): static
1120
    {
1121
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
5,011✔
1122
        $this->getCell($cellAddress)->setValue($value, $binder);
5,011✔
1123

1124
        return $this;
5,011✔
1125
    }
1126

1127
    /**
1128
     * Set a cell value.
1129
     *
1130
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1131
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1132
     * @param mixed $value Value of the cell
1133
     * @param string $dataType Explicit data type, see DataType::TYPE_*
1134
     *        Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
1135
     *             method, then it is your responsibility as an end-user developer to validate that the value and
1136
     *             the datatype match.
1137
     *       If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype
1138
     *          that you specify.
1139
     *
1140
     * @see DataType
1141
     *
1142
     * @return $this
1143
     */
1144
    public function setCellValueExplicit(CellAddress|string|array $coordinate, mixed $value, string $dataType): static
1145
    {
1146
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
104✔
1147
        $this->getCell($cellAddress)->setValueExplicit($value, $dataType);
104✔
1148

1149
        return $this;
104✔
1150
    }
1151

1152
    /**
1153
     * Get cell at a specific coordinate.
1154
     *
1155
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1156
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1157
     *
1158
     * @return Cell Cell that was found or created
1159
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1160
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1161
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1162
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1163
     *              the active cell has changed.
1164
     */
1165
    public function getCell(CellAddress|string|array $coordinate): Cell
1166
    {
1167
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
10,278✔
1168

1169
        // Shortcut for increased performance for the vast majority of simple cases
1170
        if ($this->cellCollection->has($cellAddress)) {
10,278✔
1171
            /** @var Cell $cell */
1172
            $cell = $this->cellCollection->get($cellAddress);
10,257✔
1173

1174
            return $cell;
10,257✔
1175
        }
1176

1177
        /** @var Worksheet $sheet */
1178
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
10,277✔
1179
        $cell = $sheet->getCellCollection()->get($finalCoordinate);
10,277✔
1180

1181
        return $cell ?? $sheet->createNewCell($finalCoordinate);
10,277✔
1182
    }
1183

1184
    /**
1185
     * Get the correct Worksheet and coordinate from a coordinate that may
1186
     * contains reference to another sheet or a named range.
1187
     *
1188
     * @return array{0: Worksheet, 1: string}
1189
     */
1190
    private function getWorksheetAndCoordinate(string $coordinate): array
1191
    {
1192
        $sheet = null;
10,300✔
1193
        $finalCoordinate = null;
10,300✔
1194

1195
        // Worksheet reference?
1196
        if (str_contains($coordinate, '!')) {
10,300✔
1197
            $worksheetReference = self::extractSheetTitle($coordinate, true, true);
×
1198

1199
            $sheet = $this->getParentOrThrow()->getSheetByName($worksheetReference[0]);
×
1200
            $finalCoordinate = strtoupper($worksheetReference[1]);
×
1201

1202
            if ($sheet === null) {
×
1203
                throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
×
1204
            }
1205
        } elseif (
1206
            !Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate)
10,300✔
1207
            && Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate)
10,300✔
1208
        ) {
1209
            // Named range?
1210
            $namedRange = $this->validateNamedRange($coordinate, true);
17✔
1211
            if ($namedRange !== null) {
17✔
1212
                $sheet = $namedRange->getWorksheet();
12✔
1213
                if ($sheet === null) {
12✔
1214
                    throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
×
1215
                }
1216

1217
                /** @phpstan-ignore-next-line */
1218
                $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
12✔
1219
                $finalCoordinate = str_replace('$', '', $cellCoordinate);
12✔
1220
            }
1221
        }
1222

1223
        if ($sheet === null || $finalCoordinate === null) {
10,300✔
1224
            $sheet = $this;
10,300✔
1225
            $finalCoordinate = strtoupper($coordinate);
10,300✔
1226
        }
1227

1228
        if (Coordinate::coordinateIsRange($finalCoordinate)) {
10,300✔
1229
            throw new Exception('Cell coordinate string can not be a range of cells.');
2✔
1230
        }
1231
        $finalCoordinate = str_replace('$', '', $finalCoordinate);
10,300✔
1232

1233
        return [$sheet, $finalCoordinate];
10,300✔
1234
    }
1235

1236
    /**
1237
     * Get an existing cell at a specific coordinate, or null.
1238
     *
1239
     * @param string $coordinate Coordinate of the cell, eg: 'A1'
1240
     *
1241
     * @return null|Cell Cell that was found or null
1242
     */
1243
    private function getCellOrNull(string $coordinate): ?Cell
1244
    {
1245
        // Check cell collection
1246
        if ($this->cellCollection->has($coordinate)) {
65✔
1247
            return $this->cellCollection->get($coordinate);
65✔
1248
        }
1249

1250
        return null;
×
1251
    }
1252

1253
    /**
1254
     * Create a new cell at the specified coordinate.
1255
     *
1256
     * @param string $coordinate Coordinate of the cell
1257
     *
1258
     * @return Cell Cell that was created
1259
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1260
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1261
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1262
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1263
     *              the active cell has changed.
1264
     */
1265
    public function createNewCell(string $coordinate): Cell
1266
    {
1267
        [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate);
10,277✔
1268
        $cell = new Cell(null, DataType::TYPE_NULL, $this);
10,277✔
1269
        $this->cellCollection->add($coordinate, $cell);
10,277✔
1270

1271
        // Coordinates
1272
        if ($column > $this->cachedHighestColumn) {
10,277✔
1273
            $this->cachedHighestColumn = $column;
7,081✔
1274
        }
1275
        if ($row > $this->cachedHighestRow) {
10,277✔
1276
            $this->cachedHighestRow = $row;
8,632✔
1277
        }
1278

1279
        // Cell needs appropriate xfIndex from dimensions records
1280
        //    but don't create dimension records if they don't already exist
1281
        $rowDimension = $this->rowDimensions[$row] ?? null;
10,277✔
1282
        $columnDimension = $this->columnDimensions[$columnString] ?? null;
10,277✔
1283

1284
        $xfSet = false;
10,277✔
1285
        if ($rowDimension !== null) {
10,277✔
1286
            $rowXf = (int) $rowDimension->getXfIndex();
394✔
1287
            if ($rowXf > 0) {
394✔
1288
                // then there is a row dimension with explicit style, assign it to the cell
1289
                $cell->setXfIndex($rowXf);
203✔
1290
                $xfSet = true;
203✔
1291
            }
1292
        }
1293
        if (!$xfSet && $columnDimension !== null) {
10,277✔
1294
            $colXf = (int) $columnDimension->getXfIndex();
570✔
1295
            if ($colXf > 0) {
570✔
1296
                // then there is a column dimension, assign it to the cell
1297
                $cell->setXfIndex($colXf);
215✔
1298
            }
1299
        }
1300

1301
        return $cell;
10,277✔
1302
    }
1303

1304
    /**
1305
     * Does the cell at a specific coordinate exist?
1306
     *
1307
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1308
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1309
     */
1310
    public function cellExists(CellAddress|string|array $coordinate): bool
1311
    {
1312
        $cellAddress = Validations::validateCellAddress($coordinate);
10,216✔
1313
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
10,216✔
1314

1315
        return $sheet->getCellCollection()->has($finalCoordinate);
10,216✔
1316
    }
1317

1318
    /**
1319
     * Get row dimension at a specific row.
1320
     *
1321
     * @param int $row Numeric index of the row
1322
     */
1323
    public function getRowDimension(int $row): RowDimension
1324
    {
1325
        // Get row dimension
1326
        if (!isset($this->rowDimensions[$row])) {
562✔
1327
            $this->rowDimensions[$row] = new RowDimension($row);
562✔
1328

1329
            $this->cachedHighestRow = max($this->cachedHighestRow, $row);
562✔
1330
        }
1331

1332
        return $this->rowDimensions[$row];
562✔
1333
    }
1334

1335
    public function getRowStyle(int $row): ?Style
1336
    {
1337
        return $this->parent?->getCellXfByIndexOrNull(
1✔
1338
            ($this->rowDimensions[$row] ?? null)?->getXfIndex()
1✔
1339
        );
1✔
1340
    }
1341

1342
    public function rowDimensionExists(int $row): bool
1343
    {
1344
        return isset($this->rowDimensions[$row]);
630✔
1345
    }
1346

1347
    public function columnDimensionExists(string $column): bool
1348
    {
1349
        return isset($this->columnDimensions[$column]);
39✔
1350
    }
1351

1352
    /**
1353
     * Get column dimension at a specific column.
1354
     *
1355
     * @param string $column String index of the column eg: 'A'
1356
     */
1357
    public function getColumnDimension(string $column): ColumnDimension
1358
    {
1359
        // Uppercase coordinate
1360
        $column = strtoupper($column);
665✔
1361

1362
        // Fetch dimensions
1363
        if (!isset($this->columnDimensions[$column])) {
665✔
1364
            $this->columnDimensions[$column] = new ColumnDimension($column);
665✔
1365

1366
            $columnIndex = Coordinate::columnIndexFromString($column);
665✔
1367
            if ($this->cachedHighestColumn < $columnIndex) {
665✔
1368
                $this->cachedHighestColumn = $columnIndex;
463✔
1369
            }
1370
        }
1371

1372
        return $this->columnDimensions[$column];
665✔
1373
    }
1374

1375
    /**
1376
     * Get column dimension at a specific column by using numeric cell coordinates.
1377
     *
1378
     * @param int $columnIndex Numeric column coordinate of the cell
1379
     */
1380
    public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
1381
    {
1382
        return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
110✔
1383
    }
1384

1385
    public function getColumnStyle(string $column): ?Style
1386
    {
1387
        return $this->parent?->getCellXfByIndexOrNull(
1✔
1388
            ($this->columnDimensions[$column] ?? null)?->getXfIndex()
1✔
1389
        );
1✔
1390
    }
1391

1392
    /**
1393
     * Get style for cell.
1394
     *
1395
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $cellCoordinate
1396
     *              A simple string containing a cell address like 'A1' or a cell range like 'A1:E10'
1397
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1398
     *              or a CellAddress or AddressRange object.
1399
     */
1400
    public function getStyle(AddressRange|CellAddress|int|string|array $cellCoordinate): Style
1401
    {
1402
        if (is_string($cellCoordinate)) {
10,251✔
1403
            $cellCoordinate = Validations::definedNameToCoordinate($cellCoordinate, $this);
10,249✔
1404
        }
1405
        $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate);
10,251✔
1406
        $cellCoordinate = str_replace('$', '', $cellCoordinate);
10,251✔
1407

1408
        // set this sheet as active
1409
        $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this));
10,251✔
1410

1411
        // set cell coordinate as active
1412
        $this->setSelectedCells($cellCoordinate);
10,251✔
1413

1414
        return $this->getParentOrThrow()->getCellXfSupervisor();
10,251✔
1415
    }
1416

1417
    /**
1418
     * Get table styles set for the for given cell.
1419
     *
1420
     * @param Cell $cell
1421
     *              The Cell for which the tables are retrieved
1422
     *
1423
     * @return mixed[]
1424
     */
1425
    public function getTablesWithStylesForCell(Cell $cell): array
1426
    {
1427
        $retVal = [];
550✔
1428

1429
        foreach ($this->tableCollection as $table) {
550✔
1430
            /** @var Table $table */
1431
            $dxfsTableStyle = $table->getStyle()->getTableDxfsStyle();
4✔
1432
            if ($dxfsTableStyle !== null) {
4✔
1433
                if ($dxfsTableStyle->getHeaderRowStyle() !== null || $dxfsTableStyle->getFirstRowStripeStyle() !== null || $dxfsTableStyle->getSecondRowStripeStyle() !== null) {
4✔
1434
                    $range = $table->getRange();
4✔
1435
                    if ($cell->isInRange($range)) {
4✔
1436
                        $retVal[] = $table;
4✔
1437
                    }
1438
                }
1439
            }
1440
        }
1441

1442
        return $retVal;
550✔
1443
    }
1444

1445
    /**
1446
     * Get conditional styles for a cell.
1447
     *
1448
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1449
     *          If a single cell is referenced, then the array of conditional styles will be returned if the cell is
1450
     *               included in a conditional style range.
1451
     *          If a range of cells is specified, then the styles will only be returned if the range matches the entire
1452
     *               range of the conditional.
1453
     * @param bool $firstOnly default true, return all matching
1454
     *          conditionals ordered by priority if false, first only if true
1455
     *
1456
     * @return Conditional[]
1457
     */
1458
    public function getConditionalStyles(string $coordinate, bool $firstOnly = true): array
1459
    {
1460
        $coordinate = strtoupper($coordinate);
792✔
1461
        if (Preg::isMatch('/[: ,]/', $coordinate)) {
792✔
1462
            return $this->conditionalStylesCollection[$coordinate] ?? [];
49✔
1463
        }
1464

1465
        $conditionalStyles = [];
768✔
1466
        foreach ($this->conditionalStylesCollection as $keyStylesOrig => $conditionalRange) {
768✔
1467
            $keyStyles = Coordinate::resolveUnionAndIntersection($keyStylesOrig);
222✔
1468
            $keyParts = explode(',', $keyStyles);
222✔
1469
            foreach ($keyParts as $keyPart) {
222✔
1470
                if ($keyPart === $coordinate) {
222✔
1471
                    if ($firstOnly) {
14✔
1472
                        return $conditionalRange;
14✔
1473
                    }
1474
                    $conditionalStyles[$keyStylesOrig] = $conditionalRange;
×
1475

1476
                    break;
×
1477
                } elseif (str_contains($keyPart, ':')) {
217✔
1478
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
212✔
1479
                        if ($firstOnly) {
198✔
1480
                            return $conditionalRange;
197✔
1481
                        }
1482
                        $conditionalStyles[$keyStylesOrig] = $conditionalRange;
1✔
1483

1484
                        break;
1✔
1485
                    }
1486
                }
1487
            }
1488
        }
1489
        $outArray = [];
594✔
1490
        foreach ($conditionalStyles as $conditionalArray) {
594✔
1491
            foreach ($conditionalArray as $conditional) {
1✔
1492
                $outArray[] = $conditional;
1✔
1493
            }
1494
        }
1495
        usort($outArray, [self::class, 'comparePriority']);
594✔
1496

1497
        return $outArray;
594✔
1498
    }
1499

1500
    private static function comparePriority(Conditional $condA, Conditional $condB): int
1501
    {
1502
        $a = $condA->getPriority();
1✔
1503
        $b = $condB->getPriority();
1✔
1504
        if ($a === $b) {
1✔
1505
            return 0;
×
1506
        }
1507
        if ($a === 0) {
1✔
1508
            return 1;
×
1509
        }
1510
        if ($b === 0) {
1✔
1511
            return -1;
×
1512
        }
1513

1514
        return ($a < $b) ? -1 : 1;
1✔
1515
    }
1516

1517
    public function getConditionalRange(string $coordinate): ?string
1518
    {
1519
        $coordinate = strtoupper($coordinate);
189✔
1520
        $cell = $this->getCell($coordinate);
189✔
1521
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
189✔
1522
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
189✔
1523
            foreach ($cellBlocks as $cellBlock) {
189✔
1524
                if ($cell->isInRange($cellBlock)) {
189✔
1525
                    return $conditionalRange;
188✔
1526
                }
1527
            }
1528
        }
1529

1530
        return null;
3✔
1531
    }
1532

1533
    /**
1534
     * Do conditional styles exist for this cell?
1535
     *
1536
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1537
     *          If a single cell is specified, then this method will return true if that cell is included in a
1538
     *               conditional style range.
1539
     *          If a range of cells is specified, then true will only be returned if the range matches the entire
1540
     *               range of the conditional.
1541
     */
1542
    public function conditionalStylesExists(string $coordinate): bool
1543
    {
1544
        return !empty($this->getConditionalStyles($coordinate));
22✔
1545
    }
1546

1547
    /**
1548
     * Removes conditional styles for a cell.
1549
     *
1550
     * @param string $coordinate eg: 'A1'
1551
     *
1552
     * @return $this
1553
     */
1554
    public function removeConditionalStyles(string $coordinate): static
1555
    {
1556
        unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
54✔
1557

1558
        return $this;
54✔
1559
    }
1560

1561
    /**
1562
     * Get collection of conditional styles.
1563
     *
1564
     * @return Conditional[][]
1565
     */
1566
    public function getConditionalStylesCollection(): array
1567
    {
1568
        return $this->conditionalStylesCollection;
1,352✔
1569
    }
1570

1571
    /**
1572
     * Set conditional styles.
1573
     *
1574
     * @param string $coordinate eg: 'A1'
1575
     * @param Conditional[] $styles
1576
     *
1577
     * @return $this
1578
     */
1579
    public function setConditionalStyles(string $coordinate, array $styles): static
1580
    {
1581
        $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
345✔
1582

1583
        return $this;
345✔
1584
    }
1585

1586
    /**
1587
     * Duplicate cell style to a range of cells.
1588
     *
1589
     * Please note that this will overwrite existing cell styles for cells in range!
1590
     *
1591
     * @param Style $style Cell style to duplicate
1592
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1593
     *
1594
     * @return $this
1595
     */
1596
    public function duplicateStyle(Style $style, string $range): static
1597
    {
1598
        // Add the style to the workbook if necessary
1599
        $workbook = $this->getParentOrThrow();
2✔
1600
        if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) {
2✔
1601
            // there is already such cell Xf in our collection
1602
            $xfIndex = $existingStyle->getIndex();
1✔
1603
        } else {
1604
            // we don't have such a cell Xf, need to add
1605
            $workbook->addCellXf($style);
2✔
1606
            $xfIndex = $style->getIndex();
2✔
1607
        }
1608

1609
        // Calculate range outer borders
1610
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
2✔
1611

1612
        // Make sure we can loop upwards on rows and columns
1613
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
2✔
1614
            $tmp = $rangeStart;
×
1615
            $rangeStart = $rangeEnd;
×
1616
            $rangeEnd = $tmp;
×
1617
        }
1618

1619
        // Loop through cells and apply styles
1620
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
2✔
1621
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
2✔
1622
                $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
2✔
1623
            }
1624
        }
1625

1626
        return $this;
2✔
1627
    }
1628

1629
    /**
1630
     * Duplicate conditional style to a range of cells.
1631
     *
1632
     * Please note that this will overwrite existing cell styles for cells in range!
1633
     *
1634
     * @param Conditional[] $styles Cell style to duplicate
1635
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1636
     *
1637
     * @return $this
1638
     */
1639
    public function duplicateConditionalStyle(array $styles, string $range = ''): static
1640
    {
1641
        foreach ($styles as $cellStyle) {
18✔
1642
            if (!($cellStyle instanceof Conditional)) { // @phpstan-ignore-line
18✔
1643
                throw new Exception('Style is not a conditional style');
×
1644
            }
1645
        }
1646

1647
        // Calculate range outer borders
1648
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
18✔
1649

1650
        // Make sure we can loop upwards on rows and columns
1651
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
18✔
1652
            $tmp = $rangeStart;
×
1653
            $rangeStart = $rangeEnd;
×
1654
            $rangeEnd = $tmp;
×
1655
        }
1656

1657
        // Loop through cells and apply styles
1658
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
18✔
1659
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
18✔
1660
                $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
18✔
1661
            }
1662
        }
1663

1664
        return $this;
18✔
1665
    }
1666

1667
    /**
1668
     * Set break on a cell.
1669
     *
1670
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1671
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1672
     * @param int $break Break type (type of Worksheet::BREAK_*)
1673
     *
1674
     * @return $this
1675
     */
1676
    public function setBreak(CellAddress|string|array $coordinate, int $break, int $max = -1): static
1677
    {
1678
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
33✔
1679

1680
        if ($break === self::BREAK_NONE) {
33✔
1681
            unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]);
7✔
1682
        } elseif ($break === self::BREAK_ROW) {
33✔
1683
            $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
23✔
1684
        } elseif ($break === self::BREAK_COLUMN) {
19✔
1685
            $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
19✔
1686
        }
1687

1688
        return $this;
33✔
1689
    }
1690

1691
    /**
1692
     * Get breaks.
1693
     *
1694
     * @return int[]
1695
     */
1696
    public function getBreaks(): array
1697
    {
1698
        $breaks = [];
671✔
1699
        /** @var callable $compareFunction */
1700
        $compareFunction = [self::class, 'compareRowBreaks'];
671✔
1701
        uksort($this->rowBreaks, $compareFunction);
671✔
1702
        foreach ($this->rowBreaks as $break) {
671✔
1703
            $breaks[$break->getCoordinate()] = self::BREAK_ROW;
10✔
1704
        }
1705
        /** @var callable $compareFunction */
1706
        $compareFunction = [self::class, 'compareColumnBreaks'];
671✔
1707
        uksort($this->columnBreaks, $compareFunction);
671✔
1708
        foreach ($this->columnBreaks as $break) {
671✔
1709
            $breaks[$break->getCoordinate()] = self::BREAK_COLUMN;
8✔
1710
        }
1711

1712
        return $breaks;
671✔
1713
    }
1714

1715
    /**
1716
     * Get row breaks.
1717
     *
1718
     * @return PageBreak[]
1719
     */
1720
    public function getRowBreaks(): array
1721
    {
1722
        /** @var callable $compareFunction */
1723
        $compareFunction = [self::class, 'compareRowBreaks'];
538✔
1724
        uksort($this->rowBreaks, $compareFunction);
538✔
1725

1726
        return $this->rowBreaks;
538✔
1727
    }
1728

1729
    protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int
1730
    {
1731
        $row1 = Coordinate::indexesFromString($coordinate1)[1];
9✔
1732
        $row2 = Coordinate::indexesFromString($coordinate2)[1];
9✔
1733

1734
        return $row1 - $row2;
9✔
1735
    }
1736

1737
    protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int
1738
    {
1739
        $column1 = Coordinate::indexesFromString($coordinate1)[0];
5✔
1740
        $column2 = Coordinate::indexesFromString($coordinate2)[0];
5✔
1741

1742
        return $column1 - $column2;
5✔
1743
    }
1744

1745
    /**
1746
     * Get column breaks.
1747
     *
1748
     * @return PageBreak[]
1749
     */
1750
    public function getColumnBreaks(): array
1751
    {
1752
        /** @var callable $compareFunction */
1753
        $compareFunction = [self::class, 'compareColumnBreaks'];
537✔
1754
        uksort($this->columnBreaks, $compareFunction);
537✔
1755

1756
        return $this->columnBreaks;
537✔
1757
    }
1758

1759
    /**
1760
     * Set merge on a cell range.
1761
     *
1762
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10'
1763
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1764
     *              or an AddressRange.
1765
     * @param string $behaviour How the merged cells should behave.
1766
     *               Possible values are:
1767
     *                   MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells
1768
     *                   MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells
1769
     *                   MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell
1770
     *
1771
     * @return $this
1772
     */
1773
    public function mergeCells(AddressRange|string|array $range, string $behaviour = self::MERGE_CELL_CONTENT_EMPTY): static
1774
    {
1775
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
174✔
1776

1777
        if (!str_contains($range, ':')) {
173✔
1778
            $range .= ":{$range}";
1✔
1779
        }
1780

1781
        if (!Preg::isMatch('/^([A-Z]+)(\d+):([A-Z]+)(\d+)$/', $range, $matches)) {
173✔
1782
            throw new Exception('Merge must be on a valid range of cells.');
1✔
1783
        }
1784

1785
        $this->mergeCells[$range] = $range;
172✔
1786
        $firstRow = (int) $matches[2];
172✔
1787
        $lastRow = (int) $matches[4];
172✔
1788
        $firstColumn = $matches[1];
172✔
1789
        $lastColumn = $matches[3];
172✔
1790
        $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn);
172✔
1791
        $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn);
172✔
1792
        $numberRows = $lastRow - $firstRow;
172✔
1793
        $numberColumns = $lastColumnIndex - $firstColumnIndex;
172✔
1794

1795
        if ($numberRows === 1 && $numberColumns === 1) {
172✔
1796
            return $this;
35✔
1797
        }
1798

1799
        // create upper left cell if it does not already exist
1800
        $upperLeft = "{$firstColumn}{$firstRow}";
165✔
1801
        if (!$this->cellExists($upperLeft)) {
165✔
1802
            $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
36✔
1803
        }
1804

1805
        if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) {
165✔
1806
            // Blank out the rest of the cells in the range (if they exist)
1807
            if ($numberRows > $numberColumns) {
58✔
1808
                $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour);
18✔
1809
            } else {
1810
                $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour);
40✔
1811
            }
1812
        }
1813

1814
        return $this;
165✔
1815
    }
1816

1817
    private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1818
    {
1819
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
18✔
1820
            ? [$this->getCell($upperLeft)->getFormattedValue()]
×
1821
            : [];
18✔
1822

1823
        foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) {
18✔
1824
            $iterator = $column->getCellIterator($firstRow);
18✔
1825
            $iterator->setIterateOnlyExistingCells(true);
18✔
1826
            foreach ($iterator as $cell) {
18✔
1827
                $row = $cell->getRow();
18✔
1828
                if ($row > $lastRow) {
18✔
1829
                    break;
8✔
1830
                }
1831
                $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
18✔
1832
            }
1833
        }
1834

1835
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
18✔
1836
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
×
1837
        }
1838
    }
1839

1840
    private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1841
    {
1842
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
40✔
1843
            ? [$this->getCell($upperLeft)->getFormattedValue()]
4✔
1844
            : [];
36✔
1845

1846
        foreach ($this->getRowIterator($firstRow, $lastRow) as $row) {
40✔
1847
            $iterator = $row->getCellIterator($firstColumn);
40✔
1848
            $iterator->setIterateOnlyExistingCells(true);
40✔
1849
            foreach ($iterator as $cell) {
40✔
1850
                $column = $cell->getColumn();
40✔
1851
                $columnIndex = Coordinate::columnIndexFromString($column);
40✔
1852
                if ($columnIndex > $lastColumnIndex) {
40✔
1853
                    break;
9✔
1854
                }
1855
                $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
40✔
1856
            }
1857
        }
1858

1859
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
40✔
1860
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
4✔
1861
        }
1862
    }
1863

1864
    /**
1865
     * @param mixed[] $leftCellValue
1866
     *
1867
     * @return mixed[]
1868
     */
1869
    public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array
1870
    {
1871
        if ($cell->getCoordinate() !== $upperLeft) {
58✔
1872
            Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance();
24✔
1873
            if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
24✔
1874
                $cellValue = $cell->getFormattedValue();
4✔
1875
                if ($cellValue !== '') {
4✔
1876
                    $leftCellValue[] = $cellValue;
4✔
1877
                }
1878
            }
1879
            $cell->setValueExplicit(null, DataType::TYPE_NULL);
24✔
1880
        }
1881

1882
        return $leftCellValue;
58✔
1883
    }
1884

1885
    /**
1886
     * Remove merge on a cell range.
1887
     *
1888
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10'
1889
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1890
     *              or an AddressRange.
1891
     *
1892
     * @return $this
1893
     */
1894
    public function unmergeCells(AddressRange|string|array $range): static
1895
    {
1896
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
23✔
1897

1898
        if (str_contains($range, ':')) {
23✔
1899
            if (isset($this->mergeCells[$range])) {
22✔
1900
                unset($this->mergeCells[$range]);
22✔
1901
            } else {
1902
                throw new Exception('Cell range ' . $range . ' not known as merged.');
×
1903
            }
1904
        } else {
1905
            throw new Exception('Merge can only be removed from a range of cells.');
1✔
1906
        }
1907

1908
        return $this;
22✔
1909
    }
1910

1911
    /**
1912
     * Get merge cells array.
1913
     *
1914
     * @return string[]
1915
     */
1916
    public function getMergeCells(): array
1917
    {
1918
        return $this->mergeCells;
1,236✔
1919
    }
1920

1921
    /**
1922
     * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
1923
     * a single cell range.
1924
     *
1925
     * @param string[] $mergeCells
1926
     *
1927
     * @return $this
1928
     */
1929
    public function setMergeCells(array $mergeCells): static
1930
    {
1931
        $this->mergeCells = $mergeCells;
122✔
1932

1933
        return $this;
122✔
1934
    }
1935

1936
    /**
1937
     * Set protection on a cell or cell range.
1938
     *
1939
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10'
1940
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1941
     *              or a CellAddress or AddressRange object.
1942
     * @param string $password Password to unlock the protection
1943
     * @param bool $alreadyHashed If the password has already been hashed, set this to true
1944
     *
1945
     * @return $this
1946
     */
1947
    public function protectCells(AddressRange|CellAddress|int|string|array $range, string $password = '', bool $alreadyHashed = false, string $name = '', string $securityDescriptor = ''): static
1948
    {
1949
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
26✔
1950

1951
        if (!$alreadyHashed && $password !== '') {
26✔
1952
            $password = Shared\PasswordHasher::hashPassword($password);
24✔
1953
        }
1954
        $this->protectedCells[$range] = new ProtectedRange($range, $password, $name, $securityDescriptor);
26✔
1955

1956
        return $this;
26✔
1957
    }
1958

1959
    /**
1960
     * Remove protection on a cell or cell range.
1961
     *
1962
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10'
1963
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1964
     *              or a CellAddress or AddressRange object.
1965
     *
1966
     * @return $this
1967
     */
1968
    public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static
1969
    {
1970
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
20✔
1971

1972
        if (isset($this->protectedCells[$range])) {
20✔
1973
            unset($this->protectedCells[$range]);
19✔
1974
        } else {
1975
            throw new Exception('Cell range ' . $range . ' not known as protected.');
1✔
1976
        }
1977

1978
        return $this;
19✔
1979
    }
1980

1981
    /**
1982
     * Get protected cells.
1983
     *
1984
     * @return ProtectedRange[]
1985
     */
1986
    public function getProtectedCellRanges(): array
1987
    {
1988
        return $this->protectedCells;
645✔
1989
    }
1990

1991
    /**
1992
     * Get Autofilter.
1993
     */
1994
    public function getAutoFilter(): AutoFilter
1995
    {
1996
        return $this->autoFilter;
842✔
1997
    }
1998

1999
    /**
2000
     * Set AutoFilter.
2001
     *
2002
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|AutoFilter|string $autoFilterOrRange
2003
     *            A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
2004
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2005
     *              or an AddressRange.
2006
     *
2007
     * @return $this
2008
     */
2009
    public function setAutoFilter(AddressRange|string|array|AutoFilter $autoFilterOrRange): static
2010
    {
2011
        if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
20✔
2012
            $this->autoFilter = $autoFilterOrRange;
×
2013
        } else {
2014
            $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange));
20✔
2015

2016
            $this->autoFilter->setRange($cellRange);
20✔
2017
        }
2018

2019
        return $this;
20✔
2020
    }
2021

2022
    /**
2023
     * Remove autofilter.
2024
     */
2025
    public function removeAutoFilter(): self
2026
    {
2027
        $this->autoFilter->setRange('');
1✔
2028

2029
        return $this;
1✔
2030
    }
2031

2032
    /**
2033
     * Get collection of Tables.
2034
     *
2035
     * @return ArrayObject<int, Table>
2036
     */
2037
    public function getTableCollection(): ArrayObject
2038
    {
2039
        return $this->tableCollection;
10,289✔
2040
    }
2041

2042
    /**
2043
     * Add Table.
2044
     *
2045
     * @return $this
2046
     */
2047
    public function addTable(Table $table): self
2048
    {
2049
        $table->setWorksheet($this);
103✔
2050
        $this->tableCollection[] = $table;
103✔
2051

2052
        return $this;
103✔
2053
    }
2054

2055
    /**
2056
     * @return string[] array of Table names
2057
     */
2058
    public function getTableNames(): array
2059
    {
2060
        $tableNames = [];
1✔
2061

2062
        foreach ($this->tableCollection as $table) {
1✔
2063
            /** @var Table $table */
2064
            $tableNames[] = $table->getName();
1✔
2065
        }
2066

2067
        return $tableNames;
1✔
2068
    }
2069

2070
    /**
2071
     * @param string $name the table name to search
2072
     *
2073
     * @return null|Table The table from the tables collection, or null if not found
2074
     */
2075
    public function getTableByName(string $name): ?Table
2076
    {
2077
        $tableIndex = $this->getTableIndexByName($name);
96✔
2078

2079
        return ($tableIndex === null) ? null : $this->tableCollection[$tableIndex];
96✔
2080
    }
2081

2082
    /**
2083
     * @param string $name the table name to search
2084
     *
2085
     * @return null|int The index of the located table in the tables collection, or null if not found
2086
     */
2087
    protected function getTableIndexByName(string $name): ?int
2088
    {
2089
        $name = StringHelper::strToUpper($name);
97✔
2090
        foreach ($this->tableCollection as $index => $table) {
97✔
2091
            /** @var Table $table */
2092
            if (StringHelper::strToUpper($table->getName()) === $name) {
63✔
2093
                return $index;
62✔
2094
            }
2095
        }
2096

2097
        return null;
40✔
2098
    }
2099

2100
    /**
2101
     * Remove Table by name.
2102
     *
2103
     * @param string $name Table name
2104
     *
2105
     * @return $this
2106
     */
2107
    public function removeTableByName(string $name): self
2108
    {
2109
        $tableIndex = $this->getTableIndexByName($name);
1✔
2110

2111
        if ($tableIndex !== null) {
1✔
2112
            unset($this->tableCollection[$tableIndex]);
1✔
2113
        }
2114

2115
        return $this;
1✔
2116
    }
2117

2118
    /**
2119
     * Remove collection of Tables.
2120
     */
2121
    public function removeTableCollection(): self
2122
    {
2123
        $this->tableCollection = new ArrayObject();
1✔
2124

2125
        return $this;
1✔
2126
    }
2127

2128
    /**
2129
     * Get Freeze Pane.
2130
     */
2131
    public function getFreezePane(): ?string
2132
    {
2133
        return $this->freezePane;
287✔
2134
    }
2135

2136
    /**
2137
     * Freeze Pane.
2138
     *
2139
     * Examples:
2140
     *
2141
     *     - A2 will freeze the rows above cell A2 (i.e row 1)
2142
     *     - B1 will freeze the columns to the left of cell B1 (i.e column A)
2143
     *     - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
2144
     *
2145
     * @param null|array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
2146
     *            or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2147
     *        Passing a null value for this argument will clear any existing freeze pane for this worksheet.
2148
     * @param null|array{0: int, 1: int}|CellAddress|string $topLeftCell default position of the right bottom pane
2149
     *            Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]),
2150
     *            or a CellAddress object.
2151
     *
2152
     * @return $this
2153
     */
2154
    public function freezePane(null|CellAddress|string|array $coordinate, null|CellAddress|string|array $topLeftCell = null, bool $frozenSplit = false): static
2155
    {
2156
        $this->panes = [
49✔
2157
            'bottomRight' => null,
49✔
2158
            'bottomLeft' => null,
49✔
2159
            'topRight' => null,
49✔
2160
            'topLeft' => null,
49✔
2161
        ];
49✔
2162
        $cellAddress = ($coordinate !== null)
49✔
2163
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate))
49✔
2164
            : null;
1✔
2165
        if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) {
49✔
2166
            throw new Exception('Freeze pane can not be set on a range of cells.');
1✔
2167
        }
2168
        $topLeftCell = ($topLeftCell !== null)
48✔
2169
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell))
37✔
2170
            : null;
36✔
2171

2172
        if ($cellAddress !== null && $topLeftCell === null) {
48✔
2173
            $coordinate = Coordinate::coordinateFromString($cellAddress);
36✔
2174
            $topLeftCell = $coordinate[0] . $coordinate[1];
36✔
2175
        }
2176

2177
        $topLeftCell = "$topLeftCell";
48✔
2178
        $this->paneTopLeftCell = $topLeftCell;
48✔
2179

2180
        $this->freezePane = $cellAddress;
48✔
2181
        $this->topLeftCell = $topLeftCell;
48✔
2182
        if ($cellAddress === null) {
48✔
2183
            $this->paneState = '';
1✔
2184
            $this->xSplit = $this->ySplit = 0;
1✔
2185
            $this->activePane = '';
1✔
2186
        } else {
2187
            $coordinates = Coordinate::indexesFromString($cellAddress);
48✔
2188
            $this->xSplit = $coordinates[0] - 1;
48✔
2189
            $this->ySplit = $coordinates[1] - 1;
48✔
2190
            if ($this->xSplit > 0 || $this->ySplit > 0) {
48✔
2191
                $this->paneState = $frozenSplit ? self::PANE_FROZENSPLIT : self::PANE_FROZEN;
47✔
2192
                $this->setSelectedCellsActivePane();
47✔
2193
            } else {
2194
                $this->paneState = '';
1✔
2195
                $this->freezePane = null;
1✔
2196
                $this->activePane = '';
1✔
2197
            }
2198
        }
2199

2200
        return $this;
48✔
2201
    }
2202

2203
    public function setTopLeftCell(string $topLeftCell): self
2204
    {
2205
        $this->topLeftCell = $topLeftCell;
47✔
2206

2207
        return $this;
47✔
2208
    }
2209

2210
    /**
2211
     * Unfreeze Pane.
2212
     *
2213
     * @return $this
2214
     */
2215
    public function unfreezePane(): static
2216
    {
2217
        return $this->freezePane(null);
1✔
2218
    }
2219

2220
    /**
2221
     * Get the default position of the right bottom pane.
2222
     */
2223
    public function getTopLeftCell(): ?string
2224
    {
2225
        return $this->topLeftCell;
478✔
2226
    }
2227

2228
    public function getPaneTopLeftCell(): string
2229
    {
2230
        return $this->paneTopLeftCell;
11✔
2231
    }
2232

2233
    public function setPaneTopLeftCell(string $paneTopLeftCell): self
2234
    {
2235
        $this->paneTopLeftCell = $paneTopLeftCell;
26✔
2236

2237
        return $this;
26✔
2238
    }
2239

2240
    public function usesPanes(): bool
2241
    {
2242
        return $this->xSplit > 0 || $this->ySplit > 0;
466✔
2243
    }
2244

2245
    public function getPane(string $position): ?Pane
2246
    {
2247
        return $this->panes[$position] ?? null;
2✔
2248
    }
2249

2250
    public function setPane(string $position, ?Pane $pane): self
2251
    {
2252
        if (array_key_exists($position, $this->panes)) {
35✔
2253
            $this->panes[$position] = $pane;
35✔
2254
        }
2255

2256
        return $this;
35✔
2257
    }
2258

2259
    /** @return (null|Pane)[] */
2260
    public function getPanes(): array
2261
    {
2262
        return $this->panes;
3✔
2263
    }
2264

2265
    public function getActivePane(): string
2266
    {
2267
        return $this->activePane;
14✔
2268
    }
2269

2270
    public function setActivePane(string $activePane): self
2271
    {
2272
        $this->activePane = array_key_exists($activePane, $this->panes) ? $activePane : '';
48✔
2273

2274
        return $this;
48✔
2275
    }
2276

2277
    public function getXSplit(): int
2278
    {
2279
        return $this->xSplit;
11✔
2280
    }
2281

2282
    public function setXSplit(int $xSplit): self
2283
    {
2284
        $this->xSplit = $xSplit;
11✔
2285
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
11✔
2286
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
1✔
2287
        }
2288

2289
        return $this;
11✔
2290
    }
2291

2292
    public function getYSplit(): int
2293
    {
2294
        return $this->ySplit;
11✔
2295
    }
2296

2297
    public function setYSplit(int $ySplit): self
2298
    {
2299
        $this->ySplit = $ySplit;
26✔
2300
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
26✔
2301
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
1✔
2302
        }
2303

2304
        return $this;
26✔
2305
    }
2306

2307
    public function getPaneState(): string
2308
    {
2309
        return $this->paneState;
21✔
2310
    }
2311

2312
    public const PANE_FROZEN = 'frozen';
2313
    public const PANE_FROZENSPLIT = 'frozenSplit';
2314
    public const PANE_SPLIT = 'split';
2315
    private const VALIDPANESTATE = [self::PANE_FROZEN, self::PANE_SPLIT, self::PANE_FROZENSPLIT];
2316
    private const VALIDFROZENSTATE = [self::PANE_FROZEN, self::PANE_FROZENSPLIT];
2317

2318
    public function setPaneState(string $paneState): self
2319
    {
2320
        $this->paneState = in_array($paneState, self::VALIDPANESTATE, true) ? $paneState : '';
26✔
2321
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
26✔
2322
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
25✔
2323
        } else {
2324
            $this->freezePane = null;
3✔
2325
        }
2326

2327
        return $this;
26✔
2328
    }
2329

2330
    /**
2331
     * Insert a new row, updating all possible related data.
2332
     *
2333
     * @param int $before Insert before this row number
2334
     * @param int $numberOfRows Number of new rows to insert
2335
     *
2336
     * @return $this
2337
     */
2338
    public function insertNewRowBefore(int $before, int $numberOfRows = 1): static
2339
    {
2340
        if ($before >= 1) {
42✔
2341
            $objReferenceHelper = ReferenceHelper::getInstance();
41✔
2342
            $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
41✔
2343
        } else {
2344
            throw new Exception('Rows can only be inserted before at least row 1.');
1✔
2345
        }
2346

2347
        return $this;
41✔
2348
    }
2349

2350
    /**
2351
     * Insert a new column, updating all possible related data.
2352
     *
2353
     * @param string $before Insert before this column Name, eg: 'A'
2354
     * @param int $numberOfColumns Number of new columns to insert
2355
     *
2356
     * @return $this
2357
     */
2358
    public function insertNewColumnBefore(string $before, int $numberOfColumns = 1): static
2359
    {
2360
        if (!is_numeric($before)) {
49✔
2361
            $objReferenceHelper = ReferenceHelper::getInstance();
48✔
2362
            $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
48✔
2363
        } else {
2364
            throw new Exception('Column references should not be numeric.');
1✔
2365
        }
2366

2367
        return $this;
48✔
2368
    }
2369

2370
    /**
2371
     * Insert a new column, updating all possible related data.
2372
     *
2373
     * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell)
2374
     * @param int $numberOfColumns Number of new columns to insert
2375
     *
2376
     * @return $this
2377
     */
2378
    public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1): static
2379
    {
2380
        if ($beforeColumnIndex >= 1) {
2✔
2381
            return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
1✔
2382
        }
2383

2384
        throw new Exception('Columns can only be inserted before at least column A (1).');
1✔
2385
    }
2386

2387
    /**
2388
     * Delete a row, updating all possible related data.
2389
     *
2390
     * @param int $row Remove rows, starting with this row number
2391
     * @param int $numberOfRows Number of rows to remove
2392
     *
2393
     * @return $this
2394
     */
2395
    public function removeRow(int $row, int $numberOfRows = 1): static
2396
    {
2397
        if ($row < 1) {
51✔
2398
            throw new Exception('Rows to be deleted should at least start from row 1.');
1✔
2399
        }
2400
        $startRow = $row;
50✔
2401
        $endRow = $startRow + $numberOfRows - 1;
50✔
2402
        $removeKeys = [];
50✔
2403
        $addKeys = [];
50✔
2404
        foreach ($this->mergeCells as $key => $value) {
50✔
2405
            if (
2406
                Preg::isMatch(
21✔
2407
                    '/^([a-z]{1,3})(\d+):([a-z]{1,3})(\d+)/i',
21✔
2408
                    $key,
21✔
2409
                    $matches
21✔
2410
                )
21✔
2411
            ) {
2412
                $startMergeInt = (int) $matches[2];
21✔
2413
                $endMergeInt = (int) $matches[4];
21✔
2414
                if ($startMergeInt >= $startRow) {
21✔
2415
                    if ($startMergeInt <= $endRow) {
21✔
2416
                        $removeKeys[] = $key;
3✔
2417
                    }
2418
                } elseif ($endMergeInt >= $startRow) {
1✔
2419
                    if ($endMergeInt <= $endRow) {
1✔
2420
                        $temp = $endMergeInt - 1;
1✔
2421
                        $removeKeys[] = $key;
1✔
2422
                        if ($temp !== $startMergeInt) {
1✔
2423
                            $temp3 = $matches[1] . $matches[2] . ':' . $matches[3] . $temp;
1✔
2424
                            $addKeys[] = $temp3;
1✔
2425
                        }
2426
                    }
2427
                }
2428
            }
2429
        }
2430
        foreach ($removeKeys as $key) {
50✔
2431
            unset($this->mergeCells[$key]);
3✔
2432
        }
2433
        foreach ($addKeys as $key) {
50✔
2434
            $this->mergeCells[$key] = $key;
1✔
2435
        }
2436

2437
        $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows);
50✔
2438
        $highestRow = $this->getHighestDataRow();
50✔
2439
        $removedRowsCounter = 0;
50✔
2440

2441
        for ($r = 0; $r < $numberOfRows; ++$r) {
50✔
2442
            if ($row + $r <= $highestRow) {
50✔
2443
                $this->cellCollection->removeRow($row + $r);
39✔
2444
                ++$removedRowsCounter;
39✔
2445
            }
2446
        }
2447

2448
        $objReferenceHelper = ReferenceHelper::getInstance();
50✔
2449
        $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
50✔
2450
        for ($r = 0; $r < $removedRowsCounter; ++$r) {
50✔
2451
            $this->cellCollection->removeRow($highestRow);
39✔
2452
            --$highestRow;
39✔
2453
        }
2454

2455
        $this->rowDimensions = $holdRowDimensions;
50✔
2456

2457
        return $this;
50✔
2458
    }
2459

2460
    /** @return RowDimension[] */
2461
    private function removeRowDimensions(int $row, int $numberOfRows): array
2462
    {
2463
        $highRow = $row + $numberOfRows - 1;
50✔
2464
        $holdRowDimensions = [];
50✔
2465
        foreach ($this->rowDimensions as $rowDimension) {
50✔
2466
            $num = $rowDimension->getRowIndex();
4✔
2467
            if ($num < $row) {
4✔
2468
                $holdRowDimensions[$num] = $rowDimension;
3✔
2469
            } elseif ($num > $highRow) {
4✔
2470
                $num -= $numberOfRows;
4✔
2471
                $cloneDimension = clone $rowDimension;
4✔
2472
                $cloneDimension->setRowIndex($num);
4✔
2473
                $holdRowDimensions[$num] = $cloneDimension;
4✔
2474
            }
2475
        }
2476

2477
        return $holdRowDimensions;
50✔
2478
    }
2479

2480
    /**
2481
     * Remove a column, updating all possible related data.
2482
     *
2483
     * @param string $column Remove columns starting with this column name, eg: 'A'
2484
     * @param int $numberOfColumns Number of columns to remove
2485
     *
2486
     * @return $this
2487
     */
2488
    public function removeColumn(string $column, int $numberOfColumns = 1): static
2489
    {
2490
        if (is_numeric($column)) {
43✔
2491
            throw new Exception('Column references should not be numeric.');
1✔
2492
        }
2493
        $startColumnInt = Coordinate::columnIndexFromString($column);
42✔
2494
        $endColumnInt = $startColumnInt + $numberOfColumns - 1;
42✔
2495
        $removeKeys = [];
42✔
2496
        $addKeys = [];
42✔
2497
        foreach ($this->mergeCells as $key => $value) {
42✔
2498
            if (
2499
                Preg::isMatch(
19✔
2500
                    '/^([a-z]{1,3})(\d+):([a-z]{1,3})(\d+)/i',
19✔
2501
                    $key,
19✔
2502
                    $matches
19✔
2503
                )
19✔
2504
            ) {
2505
                $startMergeInt = Coordinate::columnIndexFromString($matches[1]);
19✔
2506
                $endMergeInt = Coordinate::columnIndexFromString($matches[3]);
19✔
2507
                if ($startMergeInt >= $startColumnInt) {
19✔
2508
                    if ($startMergeInt <= $endColumnInt) {
2✔
2509
                        $removeKeys[] = $key;
2✔
2510
                    }
2511
                } elseif ($endMergeInt >= $startColumnInt) {
18✔
2512
                    if ($endMergeInt <= $endColumnInt) {
18✔
2513
                        $temp = Coordinate::columnIndexFromString($matches[3]) - 1;
1✔
2514
                        $temp2 = Coordinate::stringFromColumnIndex($temp);
1✔
2515
                        $removeKeys[] = $key;
1✔
2516
                        if ($temp2 !== $matches[1]) {
1✔
2517
                            $temp3 = $matches[1] . $matches[2] . ':' . $temp2 . $matches[4];
1✔
2518
                            $addKeys[] = $temp3;
1✔
2519
                        }
2520
                    }
2521
                }
2522
            }
2523
        }
2524
        foreach ($removeKeys as $key) {
42✔
2525
            unset($this->mergeCells[$key]);
2✔
2526
        }
2527
        foreach ($addKeys as $key) {
42✔
2528
            $this->mergeCells[$key] = $key;
1✔
2529
        }
2530

2531
        $highestColumn = $this->getHighestDataColumn();
42✔
2532
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
42✔
2533
        $pColumnIndex = Coordinate::columnIndexFromString($column);
42✔
2534

2535
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
42✔
2536

2537
        $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
42✔
2538
        $objReferenceHelper = ReferenceHelper::getInstance();
42✔
2539
        $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
42✔
2540

2541
        $this->columnDimensions = $holdColumnDimensions;
42✔
2542

2543
        if ($pColumnIndex > $highestColumnIndex) {
42✔
2544
            return $this;
9✔
2545
        }
2546

2547
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
33✔
2548

2549
        for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
33✔
2550
            $this->cellCollection->removeColumn($highestColumn);
33✔
2551
            $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
33✔
2552
        }
2553

2554
        $this->garbageCollect();
33✔
2555

2556
        return $this;
33✔
2557
    }
2558

2559
    /** @return ColumnDimension[] */
2560
    private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array
2561
    {
2562
        $highCol = $pColumnIndex + $numberOfColumns - 1;
42✔
2563
        $holdColumnDimensions = [];
42✔
2564
        foreach ($this->columnDimensions as $columnDimension) {
42✔
2565
            $num = $columnDimension->getColumnNumeric();
18✔
2566
            if ($num < $pColumnIndex) {
18✔
2567
                $str = $columnDimension->getColumnIndex();
18✔
2568
                $holdColumnDimensions[$str] = $columnDimension;
18✔
2569
            } elseif ($num > $highCol) {
18✔
2570
                $cloneDimension = clone $columnDimension;
18✔
2571
                $cloneDimension->setColumnNumeric($num - $numberOfColumns);
18✔
2572
                $str = $cloneDimension->getColumnIndex();
18✔
2573
                $holdColumnDimensions[$str] = $cloneDimension;
18✔
2574
            }
2575
        }
2576

2577
        return $holdColumnDimensions;
42✔
2578
    }
2579

2580
    /**
2581
     * Remove a column, updating all possible related data.
2582
     *
2583
     * @param int $columnIndex Remove starting with this column Index (numeric column coordinate)
2584
     * @param int $numColumns Number of columns to remove
2585
     *
2586
     * @return $this
2587
     */
2588
    public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static
2589
    {
2590
        if ($columnIndex >= 1) {
3✔
2591
            return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2✔
2592
        }
2593

2594
        throw new Exception('Columns to be deleted should at least start from column A (1)');
1✔
2595
    }
2596

2597
    /**
2598
     * Show gridlines?
2599
     */
2600
    public function getShowGridlines(): bool
2601
    {
2602
        return $this->showGridlines;
1,067✔
2603
    }
2604

2605
    /**
2606
     * Set show gridlines.
2607
     *
2608
     * @param bool $showGridLines Show gridlines (true/false)
2609
     *
2610
     * @return $this
2611
     */
2612
    public function setShowGridlines(bool $showGridLines): self
2613
    {
2614
        $this->showGridlines = $showGridLines;
862✔
2615

2616
        return $this;
862✔
2617
    }
2618

2619
    /**
2620
     * Print gridlines?
2621
     */
2622
    public function getPrintGridlines(): bool
2623
    {
2624
        return $this->printGridlines;
1,073✔
2625
    }
2626

2627
    /**
2628
     * Set print gridlines.
2629
     *
2630
     * @param bool $printGridLines Print gridlines (true/false)
2631
     *
2632
     * @return $this
2633
     */
2634
    public function setPrintGridlines(bool $printGridLines): self
2635
    {
2636
        $this->printGridlines = $printGridLines;
581✔
2637

2638
        return $this;
581✔
2639
    }
2640

2641
    /**
2642
     * Show row and column headers?
2643
     */
2644
    public function getShowRowColHeaders(): bool
2645
    {
2646
        return $this->showRowColHeaders;
534✔
2647
    }
2648

2649
    /**
2650
     * Set show row and column headers.
2651
     *
2652
     * @param bool $showRowColHeaders Show row and column headers (true/false)
2653
     *
2654
     * @return $this
2655
     */
2656
    public function setShowRowColHeaders(bool $showRowColHeaders): self
2657
    {
2658
        $this->showRowColHeaders = $showRowColHeaders;
397✔
2659

2660
        return $this;
397✔
2661
    }
2662

2663
    /**
2664
     * Show summary below? (Row/Column outlining).
2665
     */
2666
    public function getShowSummaryBelow(): bool
2667
    {
2668
        return $this->showSummaryBelow;
535✔
2669
    }
2670

2671
    /**
2672
     * Set show summary below.
2673
     *
2674
     * @param bool $showSummaryBelow Show summary below (true/false)
2675
     *
2676
     * @return $this
2677
     */
2678
    public function setShowSummaryBelow(bool $showSummaryBelow): self
2679
    {
2680
        $this->showSummaryBelow = $showSummaryBelow;
406✔
2681

2682
        return $this;
406✔
2683
    }
2684

2685
    /**
2686
     * Show summary right? (Row/Column outlining).
2687
     */
2688
    public function getShowSummaryRight(): bool
2689
    {
2690
        return $this->showSummaryRight;
535✔
2691
    }
2692

2693
    /**
2694
     * Set show summary right.
2695
     *
2696
     * @param bool $showSummaryRight Show summary right (true/false)
2697
     *
2698
     * @return $this
2699
     */
2700
    public function setShowSummaryRight(bool $showSummaryRight): self
2701
    {
2702
        $this->showSummaryRight = $showSummaryRight;
406✔
2703

2704
        return $this;
406✔
2705
    }
2706

2707
    /**
2708
     * Get comments.
2709
     *
2710
     * @return Comment[]
2711
     */
2712
    public function getComments(): array
2713
    {
2714
        return $this->comments;
1,125✔
2715
    }
2716

2717
    /**
2718
     * Set comments array for the entire sheet.
2719
     *
2720
     * @param Comment[] $comments
2721
     *
2722
     * @return $this
2723
     */
2724
    public function setComments(array $comments): self
2725
    {
2726
        $this->comments = $comments;
122✔
2727

2728
        return $this;
122✔
2729
    }
2730

2731
    /**
2732
     * Remove comment from cell.
2733
     *
2734
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2735
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2736
     *
2737
     * @return $this
2738
     */
2739
    public function removeComment(CellAddress|string|array $cellCoordinate): self
2740
    {
2741
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
56✔
2742

2743
        if (Coordinate::coordinateIsRange($cellAddress)) {
56✔
2744
            throw new Exception('Cell coordinate string can not be a range of cells.');
1✔
2745
        } elseif (str_contains($cellAddress, '$')) {
55✔
2746
            throw new Exception('Cell coordinate string must not be absolute.');
1✔
2747
        } elseif ($cellAddress == '') {
54✔
2748
            throw new Exception('Cell coordinate can not be zero-length string.');
1✔
2749
        }
2750
        // Check if we have a comment for this cell and delete it
2751
        if (isset($this->comments[$cellAddress])) {
53✔
2752
            unset($this->comments[$cellAddress]);
2✔
2753
        }
2754

2755
        return $this;
53✔
2756
    }
2757

2758
    /**
2759
     * Get comment for cell.
2760
     *
2761
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2762
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2763
     */
2764
    public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment
2765
    {
2766
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
110✔
2767

2768
        if (Coordinate::coordinateIsRange($cellAddress)) {
110✔
2769
            throw new Exception('Cell coordinate string can not be a range of cells.');
1✔
2770
        } elseif (str_contains($cellAddress, '$')) {
109✔
2771
            throw new Exception('Cell coordinate string must not be absolute.');
1✔
2772
        } elseif ($cellAddress == '') {
108✔
2773
            throw new Exception('Cell coordinate can not be zero-length string.');
1✔
2774
        }
2775

2776
        // Check if we already have a comment for this cell.
2777
        if (isset($this->comments[$cellAddress])) {
107✔
2778
            return $this->comments[$cellAddress];
74✔
2779
        }
2780

2781
        // If not, create a new comment.
2782
        $newComment = new Comment();
107✔
2783
        if ($attachNew) {
107✔
2784
            $this->comments[$cellAddress] = $newComment;
107✔
2785
        }
2786

2787
        return $newComment;
107✔
2788
    }
2789

2790
    /**
2791
     * Get active cell.
2792
     *
2793
     * @return string Example: 'A1'
2794
     */
2795
    public function getActiveCell(): string
2796
    {
2797
        return $this->activeCell;
10,317✔
2798
    }
2799

2800
    /**
2801
     * Get selected cells.
2802
     */
2803
    public function getSelectedCells(): string
2804
    {
2805
        return $this->selectedCells;
10,366✔
2806
    }
2807

2808
    /**
2809
     * Selected cell.
2810
     *
2811
     * @param string $coordinate Cell (i.e. A1)
2812
     *
2813
     * @return $this
2814
     */
2815
    public function setSelectedCell(string $coordinate): static
2816
    {
2817
        return $this->setSelectedCells($coordinate);
38✔
2818
    }
2819

2820
    /**
2821
     * Select a range of cells.
2822
     *
2823
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $coordinate A simple string containing a Cell range like 'A1:E10'
2824
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2825
     *              or a CellAddress or AddressRange object.
2826
     *
2827
     * @return $this
2828
     */
2829
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
2830
    {
2831
        if (is_string($coordinate)) {
10,314✔
2832
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
10,314✔
2833
        }
2834
        $coordinate = Validations::validateCellOrCellRange($coordinate);
10,314✔
2835

2836
        if (Coordinate::coordinateIsRange($coordinate)) {
10,314✔
2837
            [$first] = Coordinate::splitRange($coordinate);
502✔
2838
            $this->activeCell = $first[0];
502✔
2839
        } else {
2840
            $this->activeCell = $coordinate;
10,283✔
2841
        }
2842
        $this->selectedCells = $coordinate;
10,314✔
2843
        $this->setSelectedCellsActivePane();
10,314✔
2844

2845
        return $this;
10,314✔
2846
    }
2847

2848
    private function setSelectedCellsActivePane(): void
2849
    {
2850
        if (!empty($this->freezePane)) {
10,315✔
2851
            $coordinateC = Coordinate::indexesFromString($this->freezePane);
47✔
2852
            $coordinateT = Coordinate::indexesFromString($this->activeCell);
47✔
2853
            if ($coordinateC[0] === 1) {
47✔
2854
                $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft';
26✔
2855
            } elseif ($coordinateC[1] === 1) {
23✔
2856
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
3✔
2857
            } elseif ($coordinateT[1] <= $coordinateC[1]) {
21✔
2858
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
21✔
2859
            } else {
2860
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight';
10✔
2861
            }
2862
            $this->setActivePane($activePane);
47✔
2863
            $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell);
47✔
2864
        }
2865
    }
2866

2867
    /**
2868
     * Get right-to-left.
2869
     */
2870
    public function getRightToLeft(): bool
2871
    {
2872
        return $this->rightToLeft;
1,076✔
2873
    }
2874

2875
    /**
2876
     * Set right-to-left.
2877
     *
2878
     * @param bool $value Right-to-left true/false
2879
     *
2880
     * @return $this
2881
     */
2882
    public function setRightToLeft(bool $value): static
2883
    {
2884
        $this->rightToLeft = $value;
146✔
2885

2886
        return $this;
146✔
2887
    }
2888

2889
    /**
2890
     * Fill worksheet from values in array.
2891
     *
2892
     * @param mixed[]|mixed[][] $source Source array
2893
     * @param mixed $nullValue Value in source array that stands for blank cell
2894
     * @param string $startCell Insert array starting from this cell address as the top left coordinate
2895
     * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2896
     *
2897
     * @return $this
2898
     */
2899
    public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static
2900
    {
2901
        //    Convert a 1-D array to 2-D (for ease of looping)
2902
        if (!is_array(end($source))) {
798✔
2903
            $source = [$source];
47✔
2904
        }
2905
        /** @var mixed[][] $source */
2906

2907
        // start coordinate
2908
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
798✔
2909
        $startRow = (int) $startRow;
798✔
2910

2911
        // Loop through $source
2912
        if ($strictNullComparison) {
798✔
2913
            foreach ($source as $rowData) {
393✔
2914
                /** @var string */
2915
                $currentColumn = $startColumn;
393✔
2916
                foreach ($rowData as $cellValue) {
393✔
2917
                    if ($cellValue !== $nullValue) {
393✔
2918
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
393✔
2919
                    }
2920
                    StringHelper::stringIncrement($currentColumn);
393✔
2921
                }
2922
                ++$startRow;
393✔
2923
            }
2924
        } else {
2925
            foreach ($source as $rowData) {
406✔
2926
                $currentColumn = $startColumn;
406✔
2927
                foreach ($rowData as $cellValue) {
406✔
2928
                    if ($cellValue != $nullValue) {
405✔
2929
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
399✔
2930
                    }
2931
                    StringHelper::stringIncrement($currentColumn);
405✔
2932
                }
2933
                ++$startRow;
406✔
2934
            }
2935
        }
2936

2937
        return $this;
798✔
2938
    }
2939

2940
    /**
2941
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2942
     *
2943
     * @throws Exception
2944
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2945
     */
2946
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue): mixed
2947
    {
2948
        $returnValue = $nullValue;
181✔
2949

2950
        if ($cell->getValue() !== null) {
181✔
2951
            if ($cell->getValue() instanceof RichText) {
181✔
2952
                $returnValue = $cell->getValue()->getPlainText();
4✔
2953
            } else {
2954
                $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue();
181✔
2955
            }
2956

2957
            if ($formatData) {
181✔
2958
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
119✔
2959
                /** @var null|bool|float|int|RichText|string */
2960
                $returnValuex = $returnValue;
119✔
2961
                $returnValue = NumberFormat::toFormattedString(
119✔
2962
                    $returnValuex,
119✔
2963
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL
119✔
2964
                );
119✔
2965
            }
2966
        }
2967

2968
        return $returnValue;
181✔
2969
    }
2970

2971
    /**
2972
     * Create array from a range of cells.
2973
     *
2974
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2975
     * @param bool $calculateFormulas Should formulas be calculated?
2976
     * @param bool $formatData Should formatting be applied to cell values?
2977
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2978
     *                             True - Return rows and columns indexed by their actual row and column IDs
2979
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2980
     *                            True - Don't return values for rows/columns that are defined as hidden.
2981
     *
2982
     * @return mixed[][]
2983
     */
2984
    public function rangeToArray(
2985
        string $range,
2986
        mixed $nullValue = null,
2987
        bool $calculateFormulas = true,
2988
        bool $formatData = true,
2989
        bool $returnCellRef = false,
2990
        bool $ignoreHidden = false,
2991
        bool $reduceArrays = false
2992
    ): array {
2993
        $returnValue = [];
149✔
2994

2995
        // Loop through rows
2996
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
149✔
2997
            $returnValue[$rowRef] = $rowArray;
149✔
2998
        }
2999

3000
        // Return
3001
        return $returnValue;
149✔
3002
    }
3003

3004
    /**
3005
     * Create array from a multiple ranges of cells. (such as A1:A3,A15,B17:C17).
3006
     *
3007
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3008
     * @param bool $calculateFormulas Should formulas be calculated?
3009
     * @param bool $formatData Should formatting be applied to cell values?
3010
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3011
     *                             True - Return rows and columns indexed by their actual row and column IDs
3012
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3013
     *                            True - Don't return values for rows/columns that are defined as hidden.
3014
     *
3015
     * @return mixed[][]
3016
     */
3017
    public function rangesToArray(
3018
        string $ranges,
3019
        mixed $nullValue = null,
3020
        bool $calculateFormulas = true,
3021
        bool $formatData = true,
3022
        bool $returnCellRef = false,
3023
        bool $ignoreHidden = false,
3024
        bool $reduceArrays = false
3025
    ): array {
3026
        $returnValue = [];
3✔
3027

3028
        $parts = explode(',', $ranges);
3✔
3029
        foreach ($parts as $part) {
3✔
3030
            // Loop through rows
3031
            foreach ($this->rangeToArrayYieldRows($part, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
3✔
3032
                $returnValue[$rowRef] = $rowArray;
3✔
3033
            }
3034
        }
3035

3036
        // Return
3037
        return $returnValue;
3✔
3038
    }
3039

3040
    /**
3041
     * Create array from a range of cells, yielding each row in turn.
3042
     *
3043
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3044
     * @param bool $calculateFormulas Should formulas be calculated?
3045
     * @param bool $formatData Should formatting be applied to cell values?
3046
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3047
     *                             True - Return rows and columns indexed by their actual row and column IDs
3048
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3049
     *                            True - Don't return values for rows/columns that are defined as hidden.
3050
     *
3051
     * @return Generator<array<mixed>>
3052
     */
3053
    public function rangeToArrayYieldRows(
3054
        string $range,
3055
        mixed $nullValue = null,
3056
        bool $calculateFormulas = true,
3057
        bool $formatData = true,
3058
        bool $returnCellRef = false,
3059
        bool $ignoreHidden = false,
3060
        bool $reduceArrays = false
3061
    ) {
3062
        $range = Validations::validateCellOrCellRange($range);
181✔
3063

3064
        //    Identify the range that we need to extract from the worksheet
3065
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
181✔
3066
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
181✔
3067
        $minRow = $rangeStart[1];
181✔
3068
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
181✔
3069
        $maxRow = $rangeEnd[1];
181✔
3070
        $minColInt = $rangeStart[0];
181✔
3071
        $maxColInt = $rangeEnd[0];
181✔
3072

3073
        StringHelper::stringIncrement($maxCol);
181✔
3074
        /** @var array<string, bool> */
3075
        $hiddenColumns = [];
181✔
3076
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
181✔
3077
        $hideColumns = !empty($hiddenColumns);
181✔
3078

3079
        $keys = $this->cellCollection->getSortedCoordinatesInt();
181✔
3080
        $keyIndex = 0;
181✔
3081
        $keysCount = count($keys);
181✔
3082
        // Loop through rows
3083
        for ($row = $minRow; $row <= $maxRow; ++$row) {
181✔
3084
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
181✔
3085
                continue;
4✔
3086
            }
3087
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
181✔
3088
            $returnValue = $nullRow;
181✔
3089

3090
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
181✔
3091
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
181✔
3092

3093
            // Binary search to quickly approach the correct index
3094
            $keyIndex = intdiv($keysCount, 2);
181✔
3095
            $boundLow = 0;
181✔
3096
            $boundHigh = $keysCount - 1;
181✔
3097
            while ($boundLow <= $boundHigh) {
181✔
3098
                $keyIndex = intdiv($boundLow + $boundHigh, 2);
181✔
3099
                if ($keys[$keyIndex] < $index) {
181✔
3100
                    $boundLow = $keyIndex + 1;
149✔
3101
                } elseif ($keys[$keyIndex] > $index) {
181✔
3102
                    $boundHigh = $keyIndex - 1;
163✔
3103
                } else {
3104
                    break;
173✔
3105
                }
3106
            }
3107

3108
            // Realign to the proper index value
3109
            while ($keyIndex > 0 && $keys[$keyIndex] > $index) {
181✔
3110
                --$keyIndex;
16✔
3111
            }
3112
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
181✔
3113
                ++$keyIndex;
22✔
3114
            }
3115

3116
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
181✔
3117
                $key = $keys[$keyIndex];
181✔
3118
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
181✔
3119
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
181✔
3120
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
181✔
3121
                    $col = Coordinate::stringFromColumnIndex($thisCol);
181✔
3122
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
181✔
3123
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
181✔
3124
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
181✔
3125
                        if ($cell !== null) {
181✔
3126
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue);
181✔
3127
                            if ($reduceArrays) {
181✔
3128
                                while (is_array($value)) {
21✔
3129
                                    $value = array_shift($value);
19✔
3130
                                }
3131
                            }
3132
                            if ($value !== $nullValue) {
181✔
3133
                                $returnValue[$columnRef] = $value;
181✔
3134
                            }
3135
                        }
3136
                    }
3137
                }
3138
                ++$keyIndex;
181✔
3139
            }
3140

3141
            yield $rowRef => $returnValue;
181✔
3142
        }
3143
    }
3144

3145
    /**
3146
     * Prepare a row data filled with null values to deduplicate the memory areas for empty rows.
3147
     *
3148
     * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
3149
     * @param string $minCol Start column of the range
3150
     * @param string $maxCol End column of the range
3151
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3152
     *                              True - Return rows and columns indexed by their actual row and column IDs
3153
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3154
     *                             True - Don't return values for rows/columns that are defined as hidden.
3155
     * @param array<string, bool> $hiddenColumns
3156
     *
3157
     * @return mixed[]
3158
     */
3159
    private function buildNullRow(
3160
        mixed $nullValue,
3161
        string $minCol,
3162
        string $maxCol,
3163
        bool $returnCellRef,
3164
        bool $ignoreHidden,
3165
        array &$hiddenColumns
3166
    ): array {
3167
        $nullRow = [];
181✔
3168
        $c = -1;
181✔
3169
        for ($col = $minCol; $col !== $maxCol; StringHelper::stringIncrement($col)) {
181✔
3170
            if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) {
181✔
3171
                $hiddenColumns[$col] = true;
2✔
3172
            } else {
3173
                $columnRef = $returnCellRef ? $col : ++$c;
181✔
3174
                $nullRow[$columnRef] = $nullValue;
181✔
3175
            }
3176
        }
3177

3178
        return $nullRow;
181✔
3179
    }
3180

3181
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
3182
    {
3183
        $namedRange = DefinedName::resolveName($definedName, $this);
19✔
3184
        if ($namedRange === null) {
19✔
3185
            if ($returnNullIfInvalid) {
6✔
3186
                return null;
5✔
3187
            }
3188

3189
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
1✔
3190
        }
3191

3192
        if ($namedRange->isFormula()) {
13✔
3193
            if ($returnNullIfInvalid) {
×
3194
                return null;
×
3195
            }
3196

3197
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
×
3198
        }
3199

3200
        if ($namedRange->getLocalOnly()) {
13✔
3201
            $worksheet = $namedRange->getWorksheet();
2✔
3202
            if ($worksheet === null || $this !== $worksheet) {
2✔
3203
                if ($returnNullIfInvalid) {
×
NEW
3204
                    return null;
×
3205
                }
3206

3207
                throw new Exception(
×
3208
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
×
3209
                );
×
3210
            }
3211
        }
3212

3213
        return $namedRange;
13✔
3214
    }
3215

3216
    /**
3217
     * Create array from a range of cells.
3218
     *
3219
     * @param string $definedName The Named Range that should be returned
3220
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3221
     * @param bool $calculateFormulas Should formulas be calculated?
3222
     * @param bool $formatData Should formatting be applied to cell values?
3223
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3224
     *                             True - Return rows and columns indexed by their actual row and column IDs
3225
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3226
     *                            True - Don't return values for rows/columns that are defined as hidden.
3227
     *
3228
     * @return mixed[][]
3229
     */
3230
    public function namedRangeToArray(
3231
        string $definedName,
3232
        mixed $nullValue = null,
3233
        bool $calculateFormulas = true,
3234
        bool $formatData = true,
3235
        bool $returnCellRef = false,
3236
        bool $ignoreHidden = false,
3237
        bool $reduceArrays = false
3238
    ): array {
3239
        $retVal = [];
2✔
3240
        $namedRange = $this->validateNamedRange($definedName);
2✔
3241
        if ($namedRange !== null) {
1✔
3242
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
1✔
3243
            $cellRange = str_replace('$', '', $cellRange);
1✔
3244
            $workSheet = $namedRange->getWorksheet();
1✔
3245
            if ($workSheet !== null) {
1✔
3246
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
1✔
3247
            }
3248
        }
3249

3250
        return $retVal;
1✔
3251
    }
3252

3253
    /**
3254
     * Create array from worksheet.
3255
     *
3256
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3257
     * @param bool $calculateFormulas Should formulas be calculated?
3258
     * @param bool $formatData Should formatting be applied to cell values?
3259
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3260
     *                             True - Return rows and columns indexed by their actual row and column IDs
3261
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3262
     *                            True - Don't return values for rows/columns that are defined as hidden.
3263
     *
3264
     * @return mixed[][]
3265
     */
3266
    public function toArray(
3267
        mixed $nullValue = null,
3268
        bool $calculateFormulas = true,
3269
        bool $formatData = true,
3270
        bool $returnCellRef = false,
3271
        bool $ignoreHidden = false,
3272
        bool $reduceArrays = false
3273
    ): array {
3274
        // Garbage collect...
3275
        $this->garbageCollect();
80✔
3276
        $this->calculateArrays($calculateFormulas);
80✔
3277

3278
        //    Identify the range that we need to extract from the worksheet
3279
        $maxCol = $this->getHighestColumn();
80✔
3280
        $maxRow = $this->getHighestRow();
80✔
3281

3282
        // Return
3283
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
80✔
3284
    }
3285

3286
    /**
3287
     * Get row iterator.
3288
     *
3289
     * @param int $startRow The row number at which to start iterating
3290
     * @param ?int $endRow The row number at which to stop iterating
3291
     */
3292
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
3293
    {
3294
        return new RowIterator($this, $startRow, $endRow);
95✔
3295
    }
3296

3297
    /**
3298
     * Get column iterator.
3299
     *
3300
     * @param string $startColumn The column address at which to start iterating
3301
     * @param ?string $endColumn The column address at which to stop iterating
3302
     */
3303
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
3304
    {
3305
        return new ColumnIterator($this, $startColumn, $endColumn);
26✔
3306
    }
3307

3308
    /**
3309
     * Run PhpSpreadsheet garbage collector.
3310
     *
3311
     * @return $this
3312
     */
3313
    public function garbageCollect(): static
3314
    {
3315
        // Flush cache
3316
        $this->cellCollection->get('A1');
1,194✔
3317

3318
        // Lookup highest column and highest row if cells are cleaned
3319
        $colRow = $this->cellCollection->getHighestRowAndColumn();
1,194✔
3320
        $highestRow = $colRow['row'];
1,194✔
3321
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
1,194✔
3322

3323
        // Loop through column dimensions
3324
        foreach ($this->columnDimensions as $dimension) {
1,194✔
3325
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
169✔
3326
        }
3327

3328
        // Loop through row dimensions
3329
        foreach ($this->rowDimensions as $dimension) {
1,194✔
3330
            $highestRow = max($highestRow, $dimension->getRowIndex());
104✔
3331
        }
3332

3333
        // Cache values
3334
        if ($highestColumn < 1) {
1,194✔
UNCOV
3335
            $this->cachedHighestColumn = 1;
×
3336
        } else {
3337
            $this->cachedHighestColumn = $highestColumn;
1,194✔
3338
        }
3339
        /** @var int $highestRow */
3340
        $this->cachedHighestRow = $highestRow;
1,194✔
3341

3342
        // Return
3343
        return $this;
1,194✔
3344
    }
3345

3346
    /**
3347
     * @deprecated 5.2.0 Serves no useful purpose. No replacement.
3348
     *
3349
     * @codeCoverageIgnore
3350
     */
3351
    public function getHashInt(): int
3352
    {
3353
        return spl_object_id($this);
3354
    }
3355

3356
    /**
3357
     * Extract worksheet title from range.
3358
     *
3359
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3360
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3361
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3362
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3363
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3364
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3365
     *
3366
     * @param ?string $range Range to extract title from
3367
     * @param bool $returnRange Return range? (see example)
3368
     *
3369
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3370
     */
3371
    public static function extractSheetTitle(?string $range, bool $returnRange = false, bool $unapostrophize = false): array|null|string
3372
    {
3373
        if (empty($range)) {
10,537✔
3374
            return $returnRange ? [null, null] : null;
13✔
3375
        }
3376

3377
        // Sheet title included?
3378
        if (($sep = strrpos($range, '!')) === false) {
10,535✔
3379
            return $returnRange ? ['', $range] : '';
10,506✔
3380
        }
3381

3382
        if ($returnRange) {
1,406✔
3383
            $title = substr($range, 0, $sep);
1,406✔
3384
            if ($unapostrophize) {
1,406✔
3385
                $title = self::unApostrophizeTitle($title);
1,346✔
3386
            }
3387

3388
            return [$title, substr($range, $sep + 1)];
1,406✔
3389
        }
3390

3391
        return substr($range, $sep + 1);
7✔
3392
    }
3393

3394
    public static function unApostrophizeTitle(?string $title): string
3395
    {
3396
        $title ??= '';
1,360✔
3397
        if ($title[0] === "'" && substr($title, -1) === "'") {
1,360✔
3398
            $title = str_replace("''", "'", substr($title, 1, -1));
1,285✔
3399
        }
3400

3401
        return $title;
1,360✔
3402
    }
3403

3404
    /**
3405
     * Get hyperlink.
3406
     *
3407
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3408
     */
3409
    public function getHyperlink(string $cellCoordinate): Hyperlink
3410
    {
3411
        // return hyperlink if we already have one
3412
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
97✔
3413
            return $this->hyperlinkCollection[$cellCoordinate];
45✔
3414
        }
3415

3416
        // else create hyperlink
3417
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
97✔
3418

3419
        return $this->hyperlinkCollection[$cellCoordinate];
97✔
3420
    }
3421

3422
    /**
3423
     * Set hyperlink.
3424
     *
3425
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3426
     *
3427
     * @return $this
3428
     */
3429
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static
3430
    {
3431
        if ($hyperlink === null) {
54✔
3432
            unset($this->hyperlinkCollection[$cellCoordinate]);
53✔
3433
        } else {
3434
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
21✔
3435
        }
3436

3437
        return $this;
54✔
3438
    }
3439

3440
    /**
3441
     * Hyperlink at a specific coordinate exists?
3442
     *
3443
     * @param string $coordinate eg: 'A1'
3444
     */
3445
    public function hyperlinkExists(string $coordinate): bool
3446
    {
3447
        return isset($this->hyperlinkCollection[$coordinate]);
550✔
3448
    }
3449

3450
    /**
3451
     * Get collection of hyperlinks.
3452
     *
3453
     * @return Hyperlink[]
3454
     */
3455
    public function getHyperlinkCollection(): array
3456
    {
3457
        return $this->hyperlinkCollection;
640✔
3458
    }
3459

3460
    /**
3461
     * Get data validation.
3462
     *
3463
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3464
     */
3465
    public function getDataValidation(string $cellCoordinate): DataValidation
3466
    {
3467
        // return data validation if we already have one
3468
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
35✔
3469
            return $this->dataValidationCollection[$cellCoordinate];
26✔
3470
        }
3471

3472
        // or if cell is part of a data validation range
3473
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
28✔
3474
            $keyParts = explode(' ', $key);
12✔
3475
            foreach ($keyParts as $keyPart) {
12✔
3476
                if ($keyPart === $cellCoordinate) {
12✔
3477
                    return $dataValidation;
1✔
3478
                }
3479
                if (str_contains($keyPart, ':')) {
12✔
3480
                    if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) {
9✔
3481
                        return $dataValidation;
9✔
3482
                    }
3483
                }
3484
            }
3485
        }
3486

3487
        // else create data validation
3488
        $dataValidation = new DataValidation();
20✔
3489
        $dataValidation->setSqref($cellCoordinate);
20✔
3490
        $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
20✔
3491

3492
        return $dataValidation;
20✔
3493
    }
3494

3495
    /**
3496
     * Set data validation.
3497
     *
3498
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3499
     *
3500
     * @return $this
3501
     */
3502
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
3503
    {
3504
        if ($dataValidation === null) {
89✔
3505
            unset($this->dataValidationCollection[$cellCoordinate]);
58✔
3506
        } else {
3507
            $dataValidation->setSqref($cellCoordinate);
38✔
3508
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
38✔
3509
        }
3510

3511
        return $this;
89✔
3512
    }
3513

3514
    /**
3515
     * Data validation at a specific coordinate exists?
3516
     *
3517
     * @param string $coordinate eg: 'A1'
3518
     */
3519
    public function dataValidationExists(string $coordinate): bool
3520
    {
3521
        if (isset($this->dataValidationCollection[$coordinate])) {
25✔
3522
            return true;
23✔
3523
        }
3524
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
8✔
3525
            $keyParts = explode(' ', $key);
7✔
3526
            foreach ($keyParts as $keyPart) {
7✔
3527
                if ($keyPart === $coordinate) {
7✔
3528
                    return true;
1✔
3529
                }
3530
                if (str_contains($keyPart, ':')) {
7✔
3531
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
2✔
3532
                        return true;
2✔
3533
                    }
3534
                }
3535
            }
3536
        }
3537

3538
        return false;
6✔
3539
    }
3540

3541
    /**
3542
     * Get collection of data validations.
3543
     *
3544
     * @return DataValidation[]
3545
     */
3546
    public function getDataValidationCollection(): array
3547
    {
3548
        $collectionCells = [];
641✔
3549
        $collectionRanges = [];
641✔
3550
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
641✔
3551
            if (Preg::isMatch('/[: ]/', $key)) {
27✔
3552
                $collectionRanges[$key] = $dataValidation;
15✔
3553
            } else {
3554
                $collectionCells[$key] = $dataValidation;
22✔
3555
            }
3556
        }
3557

3558
        return array_merge($collectionCells, $collectionRanges);
641✔
3559
    }
3560

3561
    /**
3562
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3563
     *
3564
     * @return string Adjusted range value
3565
     */
3566
    public function shrinkRangeToFit(string $range): string
3567
    {
3568
        $maxCol = $this->getHighestColumn();
×
3569
        $maxRow = $this->getHighestRow();
×
3570
        $maxCol = Coordinate::columnIndexFromString($maxCol);
×
3571

3572
        $rangeBlocks = explode(' ', $range);
×
3573
        foreach ($rangeBlocks as &$rangeSet) {
×
3574
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
×
3575

3576
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
×
3577
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3578
            }
3579
            if ($rangeBoundaries[0][1] > $maxRow) {
×
3580
                $rangeBoundaries[0][1] = $maxRow;
×
3581
            }
3582
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
×
3583
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3584
            }
3585
            if ($rangeBoundaries[1][1] > $maxRow) {
×
3586
                $rangeBoundaries[1][1] = $maxRow;
×
3587
            }
3588
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
×
3589
        }
3590
        unset($rangeSet);
×
3591

3592
        return implode(' ', $rangeBlocks);
×
3593
    }
3594

3595
    /**
3596
     * Get tab color.
3597
     */
3598
    public function getTabColor(): Color
3599
    {
3600
        if ($this->tabColor === null) {
23✔
3601
            $this->tabColor = new Color();
23✔
3602
        }
3603

3604
        return $this->tabColor;
23✔
3605
    }
3606

3607
    /**
3608
     * Reset tab color.
3609
     *
3610
     * @return $this
3611
     */
3612
    public function resetTabColor(): static
3613
    {
3614
        $this->tabColor = null;
1✔
3615

3616
        return $this;
1✔
3617
    }
3618

3619
    /**
3620
     * Tab color set?
3621
     */
3622
    public function isTabColorSet(): bool
3623
    {
3624
        return $this->tabColor !== null;
536✔
3625
    }
3626

3627
    /**
3628
     * Copy worksheet (!= clone!).
3629
     */
3630
    public function copy(): static
3631
    {
3632
        return clone $this;
×
3633
    }
3634

3635
    /**
3636
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3637
     *          exist in the collection for this row. false will be returned otherwise.
3638
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3639
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3640
     *                  cells, then the row will be considered empty.
3641
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3642
     *                  string value cells, then the row will be considered empty.
3643
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3644
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3645
     *                  will be considered empty.
3646
     *
3647
     * @param int $definitionOfEmptyFlags
3648
     *              Possible Flag Values are:
3649
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3650
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3651
     */
3652
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
3653
    {
3654
        try {
3655
            $iterator = new RowIterator($this, $rowId, $rowId);
9✔
3656
            $iterator->seek($rowId);
8✔
3657
            $row = $iterator->current();
8✔
3658
        } catch (Exception) {
1✔
3659
            return true;
1✔
3660
        }
3661

3662
        return $row->isEmpty($definitionOfEmptyFlags);
8✔
3663
    }
3664

3665
    /**
3666
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3667
     *          exist in the collection for this column. false will be returned otherwise.
3668
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3669
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3670
     *                  cells, then the column will be considered empty.
3671
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3672
     *                  string value cells, then the column will be considered empty.
3673
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3674
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3675
     *                  will be considered empty.
3676
     *
3677
     * @param int $definitionOfEmptyFlags
3678
     *              Possible Flag Values are:
3679
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3680
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3681
     */
3682
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
3683
    {
3684
        try {
3685
            $iterator = new ColumnIterator($this, $columnId, $columnId);
9✔
3686
            $iterator->seek($columnId);
8✔
3687
            $column = $iterator->current();
8✔
3688
        } catch (Exception) {
1✔
3689
            return true;
1✔
3690
        }
3691

3692
        return $column->isEmpty($definitionOfEmptyFlags);
8✔
3693
    }
3694

3695
    /**
3696
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3697
     */
3698
    public function __clone()
3699
    {
3700
        foreach (get_object_vars($this) as $key => $val) {
20✔
3701
            if ($key == 'parent') {
20✔
3702
                continue;
20✔
3703
            }
3704

3705
            if (is_object($val) || (is_array($val))) {
20✔
3706
                if ($key === 'cellCollection') {
20✔
3707
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
20✔
3708
                    $this->cellCollection = $newCollection;
20✔
3709
                } elseif ($key === 'drawingCollection') {
20✔
3710
                    $currentCollection = $this->drawingCollection;
20✔
3711
                    $this->drawingCollection = new ArrayObject();
20✔
3712
                    foreach ($currentCollection as $item) {
20✔
3713
                        $newDrawing = clone $item;
4✔
3714
                        $newDrawing->setWorksheet($this);
4✔
3715
                    }
3716
                } elseif ($key === 'tableCollection') {
20✔
3717
                    $currentCollection = $this->tableCollection;
20✔
3718
                    $this->tableCollection = new ArrayObject();
20✔
3719
                    foreach ($currentCollection as $item) {
20✔
3720
                        $newTable = clone $item;
1✔
3721
                        $newTable->setName($item->getName() . 'clone');
1✔
3722
                        $this->addTable($newTable);
1✔
3723
                    }
3724
                } elseif ($key === 'chartCollection') {
20✔
3725
                    $currentCollection = $this->chartCollection;
20✔
3726
                    $this->chartCollection = new ArrayObject();
20✔
3727
                    foreach ($currentCollection as $item) {
20✔
3728
                        $newChart = clone $item;
5✔
3729
                        $this->addChart($newChart);
5✔
3730
                    }
3731
                } elseif ($key === 'autoFilter') {
20✔
3732
                    $newAutoFilter = clone $this->autoFilter;
20✔
3733
                    $this->autoFilter = $newAutoFilter;
20✔
3734
                    $this->autoFilter->setParent($this);
20✔
3735
                } else {
3736
                    $this->{$key} = unserialize(serialize($val));
20✔
3737
                }
3738
            }
3739
        }
3740
    }
3741

3742
    /**
3743
     * Define the code name of the sheet.
3744
     *
3745
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3746
     *                       silently space to underscore)
3747
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3748
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3749
     *
3750
     * @return $this
3751
     */
3752
    public function setCodeName(string $codeName, bool $validate = true): static
3753
    {
3754
        // Is this a 'rename' or not?
3755
        if ($this->getCodeName() == $codeName) {
10,737✔
3756
            return $this;
×
3757
        }
3758

3759
        if ($validate) {
10,737✔
3760
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
10,737✔
3761

3762
            // Syntax check
3763
            // throw an exception if not valid
3764
            self::checkSheetCodeName($codeName);
10,737✔
3765

3766
            // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
3767

3768
            if ($this->parent !== null) {
10,737✔
3769
                // Is there already such sheet name?
3770
                if ($this->parent->sheetCodeNameExists($codeName)) {
10,696✔
3771
                    // Use name, but append with lowest possible integer
3772

3773
                    if (StringHelper::countCharacters($codeName) > 29) {
695✔
3774
                        $codeName = StringHelper::substring($codeName, 0, 29);
×
3775
                    }
3776
                    $i = 1;
695✔
3777
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
695✔
3778
                        ++$i;
283✔
3779
                        if ($i == 10) {
283✔
3780
                            if (StringHelper::countCharacters($codeName) > 28) {
2✔
3781
                                $codeName = StringHelper::substring($codeName, 0, 28);
×
3782
                            }
3783
                        } elseif ($i == 100) {
283✔
3784
                            if (StringHelper::countCharacters($codeName) > 27) {
×
3785
                                $codeName = StringHelper::substring($codeName, 0, 27);
×
3786
                            }
3787
                        }
3788
                    }
3789

3790
                    $codeName .= '_' . $i; // ok, we have a valid name
695✔
3791
                }
3792
            }
3793
        }
3794

3795
        $this->codeName = $codeName;
10,737✔
3796

3797
        return $this;
10,737✔
3798
    }
3799

3800
    /**
3801
     * Return the code name of the sheet.
3802
     */
3803
    public function getCodeName(): ?string
3804
    {
3805
        return $this->codeName;
10,737✔
3806
    }
3807

3808
    /**
3809
     * Sheet has a code name ?
3810
     */
3811
    public function hasCodeName(): bool
3812
    {
3813
        return $this->codeName !== null;
2✔
3814
    }
3815

3816
    public static function nameRequiresQuotes(string $sheetName): bool
3817
    {
3818
        return !Preg::isMatch(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName);
4✔
3819
    }
3820

3821
    public function isRowVisible(int $row): bool
3822
    {
3823
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
121✔
3824
    }
3825

3826
    /**
3827
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3828
     */
3829
    public function isCellLocked(string $coordinate): bool
3830
    {
3831
        if ($this->getProtection()->getsheet() !== true) {
1✔
3832
            return false;
1✔
3833
        }
3834
        if ($this->cellExists($coordinate)) {
1✔
3835
            return $this->getCell($coordinate)->isLocked();
1✔
3836
        }
3837
        $spreadsheet = $this->parent;
1✔
3838
        $xfIndex = $this->getXfIndex($coordinate);
1✔
3839
        if ($spreadsheet === null || $xfIndex === null) {
1✔
3840
            return true;
1✔
3841
        }
3842

3843
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
×
3844
    }
3845

3846
    /**
3847
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3848
     */
3849
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
3850
    {
3851
        if ($this->cellExists($coordinate)) {
1✔
3852
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
1✔
3853
        }
3854

3855
        // cell doesn't exist, therefore isn't a formula,
3856
        // therefore isn't hidden on formula bar.
3857
        return false;
1✔
3858
    }
3859

3860
    private function getXfIndex(string $coordinate): ?int
3861
    {
3862
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
1✔
3863
        $row = (int) $row;
1✔
3864
        $xfIndex = null;
1✔
3865
        if ($this->rowDimensionExists($row)) {
1✔
3866
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
×
3867
        }
3868
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
1✔
3869
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
×
3870
        }
3871

3872
        return $xfIndex;
1✔
3873
    }
3874

3875
    private string $backgroundImage = '';
3876

3877
    private string $backgroundMime = '';
3878

3879
    private string $backgroundExtension = '';
3880

3881
    public function getBackgroundImage(): string
3882
    {
3883
        return $this->backgroundImage;
1,008✔
3884
    }
3885

3886
    public function getBackgroundMime(): string
3887
    {
3888
        return $this->backgroundMime;
400✔
3889
    }
3890

3891
    public function getBackgroundExtension(): string
3892
    {
3893
        return $this->backgroundExtension;
400✔
3894
    }
3895

3896
    /**
3897
     * Set background image.
3898
     * Used on read/write for Xlsx.
3899
     * Used on write for Html.
3900
     *
3901
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3902
     */
3903
    public function setBackgroundImage(string $backgroundImage): self
3904
    {
3905
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
4✔
3906
        $mime = $imageArray['mime'];
4✔
3907
        if ($mime !== '') {
4✔
3908
            $extension = explode('/', $mime);
3✔
3909
            $extension = $extension[1];
3✔
3910
            $this->backgroundImage = $backgroundImage;
3✔
3911
            $this->backgroundMime = $mime;
3✔
3912
            $this->backgroundExtension = $extension;
3✔
3913
        }
3914

3915
        return $this;
4✔
3916
    }
3917

3918
    /**
3919
     * Copy cells, adjusting relative cell references in formulas.
3920
     * Acts similarly to Excel "fill handle" feature.
3921
     *
3922
     * @param string $fromCell Single source cell, e.g. C3
3923
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3924
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3925
     */
3926
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
3927
    {
3928
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
1✔
3929
        $valueString = $this->getCell($fromCell)->getValueString();
1✔
3930
        /** @var mixed[][] */
3931
        $style = $this->getStyle($fromCell)->exportArray();
1✔
3932
        $fromIndexes = Coordinate::indexesFromString($fromCell);
1✔
3933
        $referenceHelper = ReferenceHelper::getInstance();
1✔
3934
        foreach ($toArray as $destination) {
1✔
3935
            if ($destination !== $fromCell) {
1✔
3936
                $toIndexes = Coordinate::indexesFromString($destination);
1✔
3937
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
1✔
3938
                if ($copyStyle) {
1✔
3939
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
1✔
3940
                }
3941
            }
3942
        }
3943
    }
3944

3945
    public function calculateArrays(bool $preCalculateFormulas = true): void
3946
    {
3947
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
1,169✔
3948
            $keys = $this->cellCollection->getCoordinates();
46✔
3949
            foreach ($keys as $key) {
46✔
3950
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
46✔
3951
                    if (!Preg::isMatch(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValueString())) {
46✔
3952
                        $this->getCell($key)->getCalculatedValue();
45✔
3953
                    }
3954
                }
3955
            }
3956
        }
3957
    }
3958

3959
    public function isCellInSpillRange(string $coordinate): bool
3960
    {
3961
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
2✔
3962
            return false;
1✔
3963
        }
3964
        $this->calculateArrays();
1✔
3965
        $keys = $this->cellCollection->getCoordinates();
1✔
3966
        foreach ($keys as $key) {
1✔
3967
            $attributes = $this->getCell($key)->getFormulaAttributes();
1✔
3968
            if (isset($attributes['ref'])) {
1✔
3969
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
1✔
3970
                    // false for first cell in range, true otherwise
3971
                    return $coordinate !== $key;
1✔
3972
                }
3973
            }
3974
        }
3975

3976
        return false;
1✔
3977
    }
3978

3979
    /** @param mixed[][] $styleArray */
3980
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
3981
    {
3982
        $spreadsheet = $this->parent;
2✔
3983
        if ($spreadsheet === null) {
2✔
3984
            return false;
1✔
3985
        }
3986
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
1✔
3987
        $originalSelected = $this->selectedCells;
1✔
3988
        $this->getStyle($coordinate)->applyFromArray($styleArray);
1✔
3989
        $this->setSelectedCells($originalSelected);
1✔
3990
        if ($activeSheetIndex >= 0) {
1✔
3991
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
1✔
3992
        }
3993

3994
        return true;
1✔
3995
    }
3996

3997
    public function copyFormula(string $fromCell, string $toCell): void
3998
    {
3999
        $formula = $this->getCell($fromCell)->getValue();
1✔
4000
        $newFormula = $formula;
1✔
4001
        if (is_string($formula) && $this->getCell($fromCell)->getDataType() === DataType::TYPE_FORMULA) {
1✔
4002
            [$fromColInt, $fromRow] = Coordinate::indexesFromString($fromCell);
1✔
4003
            [$toColInt, $toRow] = Coordinate::indexesFromString($toCell);
1✔
4004
            $helper = ReferenceHelper::getInstance();
1✔
4005
            $newFormula = $helper->updateFormulaReferences(
1✔
4006
                $formula,
1✔
4007
                'A1',
1✔
4008
                $toColInt - $fromColInt,
1✔
4009
                $toRow - $fromRow
1✔
4010
            );
1✔
4011
        }
4012
        $this->setCellValue($toCell, $newFormula);
1✔
4013
    }
4014
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc