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

PHPOffice / PhpSpreadsheet / 24586306065

17 Apr 2026 08:55PM UTC coverage: 97.033% (+0.1%) from 96.904%
24586306065

Pull #4830

github

web-flow
Merge e61358e37 into 9b90dee03
Pull Request #4830: Add optional XMLReader streaming mode for XLSX cell data parsing

121 of 125 new or added lines in 1 file covered. (96.8%)

161 existing lines in 8 files now uncovered.

47974 of 49441 relevant lines covered (97.03%)

385.34 hits per line

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

94.96
/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 drawings.
113
     *
114
     * @var ArrayObject<int, BaseDrawing>
115
     */
116
    private ArrayObject $inCellDrawingCollection;
117

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

125
    /**
126
     * Collection of Table objects.
127
     *
128
     * @var ArrayObject<int, Table>
129
     */
130
    private ArrayObject $tableCollection;
131

132
    /**
133
     * Worksheet title.
134
     */
135
    private string $title = '';
136

137
    /**
138
     * Sheet state.
139
     */
140
    private string $sheetState;
141

142
    /**
143
     * Page setup.
144
     */
145
    private PageSetup $pageSetup;
146

147
    /**
148
     * Page margins.
149
     */
150
    private PageMargins $pageMargins;
151

152
    /**
153
     * Page header/footer.
154
     */
155
    private HeaderFooter $headerFooter;
156

157
    /**
158
     * Sheet view.
159
     */
160
    private SheetView $sheetView;
161

162
    /**
163
     * Protection.
164
     */
165
    private Protection $protection;
166

167
    /**
168
     * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
169
     *
170
     * @var Conditional[][]
171
     */
172
    private array $conditionalStylesCollection = [];
173

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

181
    /**
182
     * Collection of column breaks.
183
     *
184
     * @var PageBreak[]
185
     */
186
    private array $columnBreaks = [];
187

188
    /**
189
     * Collection of merged cell ranges.
190
     *
191
     * @var string[]
192
     */
193
    private array $mergeCells = [];
194

195
    /**
196
     * Collection of protected cell ranges.
197
     *
198
     * @var ProtectedRange[]
199
     */
200
    private array $protectedCells = [];
201

202
    /**
203
     * Autofilter Range and selection.
204
     */
205
    private AutoFilter $autoFilter;
206

207
    /**
208
     * Freeze pane.
209
     */
210
    private ?string $freezePane = null;
211

212
    /**
213
     * Default position of the right bottom pane.
214
     */
215
    private ?string $topLeftCell = null;
216

217
    private string $paneTopLeftCell = '';
218

219
    private string $activePane = '';
220

221
    private int $xSplit = 0;
222

223
    private int $ySplit = 0;
224

225
    private string $paneState = '';
226

227
    /**
228
     * Properties of the 4 panes.
229
     *
230
     * @var (null|Pane)[]
231
     */
232
    private array $panes = [
233
        'bottomRight' => null,
234
        'bottomLeft' => null,
235
        'topRight' => null,
236
        'topLeft' => null,
237
    ];
238

239
    /**
240
     * Show gridlines?
241
     */
242
    private bool $showGridlines = true;
243

244
    /**
245
     * Print gridlines?
246
     */
247
    private bool $printGridlines = false;
248

249
    /**
250
     * Show row and column headers?
251
     */
252
    private bool $showRowColHeaders = true;
253

254
    /**
255
     * Show summary below? (Row/Column outline).
256
     */
257
    private bool $showSummaryBelow = true;
258

259
    /**
260
     * Show summary right? (Row/Column outline).
261
     */
262
    private bool $showSummaryRight = true;
263

264
    /**
265
     * Collection of comments.
266
     *
267
     * @var Comment[]
268
     */
269
    private array $comments = [];
270

271
    /**
272
     * Active cell. (Only one!).
273
     */
274
    private string $activeCell = 'A1';
275

276
    /**
277
     * Selected cells.
278
     */
279
    private string $selectedCells = 'A1';
280

281
    /**
282
     * Cached highest column.
283
     */
284
    private int $cachedHighestColumn = 1;
285

286
    /**
287
     * Cached highest row.
288
     */
289
    private int $cachedHighestRow = 1;
290

291
    /**
292
     * Right-to-left?
293
     */
294
    private bool $rightToLeft = false;
295

296
    /**
297
     * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
298
     *
299
     * @var Hyperlink[]
300
     */
301
    private array $hyperlinkCollection = [];
302

303
    /**
304
     * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
305
     * Index can include ranges, and multiple cells/ranges.
306
     *
307
     * @var DataValidation[]
308
     */
309
    private array $dataValidationCollection = [];
310

311
    /**
312
     * Tab color.
313
     */
314
    private ?Color $tabColor = null;
315

316
    /**
317
     * CodeName.
318
     */
319
    private ?string $codeName = null;
320

321
    /**
322
     * Create a new worksheet.
323
     */
324
    public function __construct(?Spreadsheet $parent = null, string $title = 'Worksheet')
11,419✔
325
    {
326
        // Set parent and title
327
        $this->parent = $parent;
11,419✔
328
        $this->setTitle($title, false);
11,419✔
329
        // setTitle can change $pTitle
330
        $this->setCodeName($this->getTitle());
11,419✔
331
        $this->setSheetState(self::SHEETSTATE_VISIBLE);
11,419✔
332

333
        $this->cellCollection = CellsFactory::getInstance($this);
11,419✔
334
        // Set page setup
335
        $this->pageSetup = new PageSetup();
11,419✔
336
        // Set page margins
337
        $this->pageMargins = new PageMargins();
11,419✔
338
        // Set page header/footer
339
        $this->headerFooter = new HeaderFooter();
11,419✔
340
        // Set sheet view
341
        $this->sheetView = new SheetView();
11,419✔
342
        // Drawing collection
343
        $this->drawingCollection = new ArrayObject();
11,419✔
344
        // In Cell Drawing collection
345
        $this->inCellDrawingCollection = new ArrayObject();
11,419✔
346
        // Chart collection
347
        $this->chartCollection = new ArrayObject();
11,419✔
348
        // Protection
349
        $this->protection = new Protection();
11,419✔
350
        // Default row dimension
351
        $this->defaultRowDimension = new RowDimension(null);
11,419✔
352
        // Default column dimension
353
        $this->defaultColumnDimension = new ColumnDimension(null);
11,419✔
354
        // AutoFilter
355
        $this->autoFilter = new AutoFilter('', $this);
11,419✔
356
        // Table collection
357
        $this->tableCollection = new ArrayObject();
11,419✔
358
    }
359

360
    /**
361
     * Disconnect all cells from this Worksheet object,
362
     * typically so that the worksheet object can be unset.
363
     */
364
    public function disconnectCells(): void
10,435✔
365
    {
366
        if (isset($this->cellCollection)) { //* @phpstan-ignore-line
10,435✔
367
            $this->cellCollection->unsetWorksheetCells();
10,435✔
368
            unset($this->cellCollection);
10,435✔
369
        }
370
        //    detach ourself from the workbook, so that it can then delete this worksheet successfully
371
        $this->parent = null;
10,435✔
372
    }
373

374
    /**
375
     * Code to execute when this worksheet is unset().
376
     */
377
    public function __destruct()
121✔
378
    {
379
        Calculation::getInstanceOrNull($this->parent)
121✔
380
            ?->clearCalculationCacheForWorksheet($this->title);
121✔
381

382
        $this->disconnectCells();
121✔
383
        unset($this->rowDimensions, $this->columnDimensions, $this->tableCollection, $this->drawingCollection, $this->inCellDrawingCollection, $this->chartCollection, $this->autoFilter);
121✔
384
    }
385

386
    /**
387
     * Return the cell collection.
388
     */
389
    public function getCellCollection(): Cells
10,981✔
390
    {
391
        return $this->cellCollection;
10,981✔
392
    }
393

394
    /**
395
     * Get array of invalid characters for sheet title.
396
     *
397
     * @return string[]
398
     */
399
    public static function getInvalidCharacters(): array
1✔
400
    {
401
        return self::INVALID_CHARACTERS;
1✔
402
    }
403

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

426
        // Enforce maximum characters allowed for sheet title
427
        if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
11,419✔
428
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
1✔
429
        }
430

431
        return $sheetCodeName;
11,419✔
432
    }
433

434
    /**
435
     * Check sheet title for valid Excel syntax.
436
     *
437
     * @param string $sheetTitle The string to check
438
     *
439
     * @return string The valid string
440
     */
441
    private static function checkSheetTitle(string $sheetTitle): string
11,419✔
442
    {
443
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ]
444
        if (str_replace(self::INVALID_CHARACTERS, '', $sheetTitle) !== $sheetTitle) {
11,419✔
445
            throw new Exception('Invalid character found in sheet title');
2✔
446
        }
447

448
        // Enforce maximum characters allowed for sheet title
449
        if (StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
11,419✔
450
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
4✔
451
        }
452

453
        return $sheetTitle;
11,419✔
454
    }
455

456
    /**
457
     * Get a sorted list of all cell coordinates currently held in the collection by row and column.
458
     *
459
     * @param bool $sorted Also sort the cell collection?
460
     *
461
     * @return string[]
462
     */
463
    public function getCoordinates(bool $sorted = true): array
1,641✔
464
    {
465
        if (!isset($this->cellCollection)) { //* @phpstan-ignore-line
1,641✔
466
            return [];
1✔
467
        }
468

469
        if ($sorted) {
1,641✔
470
            return $this->cellCollection->getSortedCoordinates();
626✔
471
        }
472

473
        return $this->cellCollection->getCoordinates();
1,494✔
474
    }
475

476
    /**
477
     * Get collection of row dimensions.
478
     *
479
     * @return RowDimension[]
480
     */
481
    public function getRowDimensions(): array
1,342✔
482
    {
483
        return $this->rowDimensions;
1,342✔
484
    }
485

486
    /**
487
     * Get default row dimension.
488
     */
489
    public function getDefaultRowDimension(): RowDimension
1,313✔
490
    {
491
        return $this->defaultRowDimension;
1,313✔
492
    }
493

494
    /**
495
     * Get collection of column dimensions.
496
     *
497
     * @return ColumnDimension[]
498
     */
499
    public function getColumnDimensions(): array
1,348✔
500
    {
501
        /** @var callable $callable */
502
        $callable = [self::class, 'columnDimensionCompare'];
1,348✔
503
        uasort($this->columnDimensions, $callable);
1,348✔
504

505
        return $this->columnDimensions;
1,348✔
506
    }
507

508
    private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int
115✔
509
    {
510
        return $a->getColumnNumeric() - $b->getColumnNumeric();
115✔
511
    }
512

513
    /**
514
     * Get default column dimension.
515
     */
516
    public function getDefaultColumnDimension(): ColumnDimension
656✔
517
    {
518
        return $this->defaultColumnDimension;
656✔
519
    }
520

521
    /**
522
     * Get collection of drawings.
523
     *
524
     * @return ArrayObject<int, BaseDrawing>
525
     */
526
    public function getDrawingCollection(): ArrayObject
1,309✔
527
    {
528
        return $this->drawingCollection;
1,309✔
529
    }
530

531
    /**
532
     * Get collection of drawings.
533
     *
534
     * @return ArrayObject<int, BaseDrawing>
535
     */
536
    public function getInCellDrawingCollection(): ArrayObject
446✔
537
    {
538
        return $this->inCellDrawingCollection;
446✔
539
    }
540

541
    /**
542
     * Get collection of charts.
543
     *
544
     * @return ArrayObject<int, Chart>
545
     */
546
    public function getChartCollection(): ArrayObject
101✔
547
    {
548
        return $this->chartCollection;
101✔
549
    }
550

551
    public function addChart(Chart $chart): Chart
107✔
552
    {
553
        $chart->setWorksheet($this);
107✔
554
        $this->chartCollection[] = $chart;
107✔
555

556
        return $chart;
107✔
557
    }
558

559
    /**
560
     * Return the count of charts on this worksheet.
561
     *
562
     * @return int The number of charts
563
     */
564
    public function getChartCount(): int
84✔
565
    {
566
        return count($this->chartCollection);
84✔
567
    }
568

569
    /**
570
     * Get a chart by its index position.
571
     *
572
     * @param ?string $index Chart index position
573
     *
574
     * @return Chart|false
575
     */
576
    public function getChartByIndex(?string $index)
79✔
577
    {
578
        $chartCount = count($this->chartCollection);
79✔
579
        if ($chartCount == 0) {
79✔
580
            return false;
×
581
        }
582
        if ($index === null) {
79✔
583
            $index = --$chartCount;
×
584
        }
585
        if (!isset($this->chartCollection[$index])) {
79✔
586
            return false;
×
587
        }
588

589
        return $this->chartCollection[$index];
79✔
590
    }
591

592
    /**
593
     * Return an array of the names of charts on this worksheet.
594
     *
595
     * @return string[] The names of charts
596
     */
597
    public function getChartNames(): array
5✔
598
    {
599
        $chartNames = [];
5✔
600
        foreach ($this->chartCollection as $chart) {
5✔
601
            $chartNames[] = $chart->getName();
5✔
602
        }
603

604
        return $chartNames;
5✔
605
    }
606

607
    /**
608
     * Get a chart by name.
609
     *
610
     * @param string $chartName Chart name
611
     *
612
     * @return Chart|false
613
     */
614
    public function getChartByName(string $chartName)
6✔
615
    {
616
        foreach ($this->chartCollection as $index => $chart) {
6✔
617
            if ($chart->getName() == $chartName) {
6✔
618
                return $chart;
6✔
619
            }
620
        }
621

622
        return false;
1✔
623
    }
624

625
    public function getChartByNameOrThrow(string $chartName): Chart
6✔
626
    {
627
        $chart = $this->getChartByName($chartName);
6✔
628
        if ($chart !== false) {
6✔
629
            return $chart;
6✔
630
        }
631

632
        throw new Exception("Sheet does not have a chart named $chartName.");
1✔
633
    }
634

635
    /**
636
     * Refresh column dimensions.
637
     *
638
     * @return $this
639
     */
640
    public function refreshColumnDimensions(): static
25✔
641
    {
642
        $newColumnDimensions = [];
25✔
643
        foreach ($this->getColumnDimensions() as $objColumnDimension) {
25✔
644
            $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
25✔
645
        }
646

647
        $this->columnDimensions = $newColumnDimensions;
25✔
648

649
        return $this;
25✔
650
    }
651

652
    /**
653
     * Refresh row dimensions.
654
     *
655
     * @return $this
656
     */
657
    public function refreshRowDimensions(): static
9✔
658
    {
659
        $newRowDimensions = [];
9✔
660
        foreach ($this->getRowDimensions() as $objRowDimension) {
9✔
661
            $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
9✔
662
        }
663

664
        $this->rowDimensions = $newRowDimensions;
9✔
665

666
        return $this;
9✔
667
    }
668

669
    /**
670
     * Calculate worksheet dimension.
671
     *
672
     * @return string String containing the dimension of this worksheet
673
     */
674
    public function calculateWorksheetDimension(): string
531✔
675
    {
676
        // Return
677
        return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
531✔
678
    }
679

680
    /**
681
     * Calculate worksheet data dimension.
682
     *
683
     * @return string String containing the dimension of this worksheet that actually contain data
684
     */
685
    public function calculateWorksheetDataDimension(): string
600✔
686
    {
687
        // Return
688
        return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
600✔
689
    }
690

691
    /**
692
     * Calculate widths for auto-size columns.
693
     *
694
     * @return $this
695
     */
696
    public function calculateColumnWidths(): static
868✔
697
    {
698
        $activeSheet = $this->getParent()?->getActiveSheetIndex();
868✔
699
        $selectedCells = $this->selectedCells;
868✔
700
        // initialize $autoSizes array
701
        $autoSizes = [];
868✔
702
        foreach ($this->getColumnDimensions() as $colDimension) {
868✔
703
            if ($colDimension->getAutoSize()) {
183✔
704
                $autoSizes[$colDimension->getColumnIndex()] = -1;
67✔
705
            }
706
        }
707

708
        // There is only something to do if there are some auto-size columns
709
        if (!empty($autoSizes)) {
868✔
710
            $holdActivePane = $this->activePane;
67✔
711
            // build list of cells references that participate in a merge
712
            $isMergeCell = [];
67✔
713
            foreach ($this->getMergeCells() as $cells) {
67✔
714
                foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
16✔
715
                    $isMergeCell[$cellReference] = true;
16✔
716
                }
717
            }
718

719
            $autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges();
67✔
720

721
            // loop through all cells in the worksheet
722
            foreach ($this->getCoordinates(false) as $coordinate) {
67✔
723
                $cell = $this->getCellOrNull($coordinate);
67✔
724

725
                if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
67✔
726
                    //Determine if cell is in merge range
727
                    $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
67✔
728

729
                    //By default merged cells should be ignored
730
                    $isMergedButProceed = false;
67✔
731

732
                    //The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide)
733
                    if ($isMerged && $cell->isMergeRangeValueCell()) {
67✔
734
                        $range = (string) $cell->getMergeRange();
×
735
                        $rangeBoundaries = Coordinate::rangeDimension($range);
×
736
                        if ($rangeBoundaries[0] === 1) {
×
737
                            $isMergedButProceed = true;
×
738
                        }
739
                    }
740

741
                    // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range
742
                    if (!$isMerged || $isMergedButProceed) {
67✔
743
                        // Determine if we need to make an adjustment for the first row in an AutoFilter range that
744
                        //    has a column filter dropdown
745
                        $filterAdjustment = false;
67✔
746
                        if (!empty($autoFilterIndentRanges)) {
67✔
747
                            foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) {
4✔
748
                                /** @var string $autoFilterFirstRowRange */
749
                                if ($cell->isInRange($autoFilterFirstRowRange)) {
4✔
750
                                    $filterAdjustment = true;
4✔
751

752
                                    break;
4✔
753
                                }
754
                            }
755
                        }
756

757
                        $indentAdjustment = $cell->getStyle()->getAlignment()->getIndent();
67✔
758
                        $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER);
67✔
759

760
                        // Calculated value
761
                        // To formatted string
762
                        $cellValue = NumberFormat::toFormattedString(
67✔
763
                            $cell->getCalculatedValueString(),
67✔
764
                            (string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
67✔
765
                                ->getNumberFormat()->getFormatCode(true)
67✔
766
                        );
67✔
767

768
                        if ($cellValue !== '') {
67✔
769
                            $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
67✔
770
                                $autoSizes[$this->cellCollection->getCurrentColumn()],
67✔
771
                                round(
67✔
772
                                    Shared\Font::calculateColumnWidth(
67✔
773
                                        $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(),
67✔
774
                                        $cellValue,
67✔
775
                                        (int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
67✔
776
                                            ->getAlignment()->getTextRotation(),
67✔
777
                                        $this->getParentOrThrow()->getDefaultStyle()->getFont(),
67✔
778
                                        $filterAdjustment,
67✔
779
                                        $indentAdjustment
67✔
780
                                    ),
67✔
781
                                    3
67✔
782
                                )
67✔
783
                            );
67✔
784
                        }
785
                    }
786
                }
787
            }
788

789
            // adjust column widths
790
            foreach ($autoSizes as $columnIndex => $width) {
67✔
791
                if ($width == -1) {
67✔
792
                    $width = $this->getDefaultColumnDimension()->getWidth();
×
793
                }
794
                $this->getColumnDimension($columnIndex)->setWidth($width);
67✔
795
            }
796
            $this->activePane = $holdActivePane;
67✔
797
        }
798
        if ($activeSheet !== null && $activeSheet >= 0) {
868✔
799
            $this->getParent()?->setActiveSheetIndex($activeSheet);
868✔
800
        }
801
        $this->setSelectedCells($selectedCells);
868✔
802

803
        return $this;
868✔
804
    }
805

806
    /**
807
     * Get parent or null.
808
     */
809
    public function getParent(): ?Spreadsheet
10,990✔
810
    {
811
        return $this->parent;
10,990✔
812
    }
813

814
    /**
815
     * Get parent, throw exception if null.
816
     */
817
    public function getParentOrThrow(): Spreadsheet
11,062✔
818
    {
819
        if ($this->parent !== null) {
11,062✔
820
            return $this->parent;
11,061✔
821
        }
822

823
        throw new Exception('Sheet does not have a parent.');
1✔
824
    }
825

826
    /**
827
     * Re-bind parent.
828
     *
829
     * @return $this
830
     */
831
    public function rebindParent(Spreadsheet $parent): static
54✔
832
    {
833
        if ($this->parent !== null) {
54✔
834
            $definedNames = $this->parent->getDefinedNames();
4✔
835
            foreach ($definedNames as $definedName) {
4✔
836
                $parent->addDefinedName($definedName);
×
837
            }
838

839
            $this->parent->removeSheetByIndex(
4✔
840
                $this->parent->getIndex($this)
4✔
841
            );
4✔
842
        }
843
        $this->parent = $parent;
54✔
844

845
        return $this;
54✔
846
    }
847

848
    public function setParent(Spreadsheet $parent): self
12✔
849
    {
850
        $this->parent = $parent;
12✔
851

852
        return $this;
12✔
853
    }
854

855
    /**
856
     * Get title.
857
     */
858
    public function getTitle(): string
11,419✔
859
    {
860
        return $this->title;
11,419✔
861
    }
862

863
    /**
864
     * Set title.
865
     *
866
     * @param string $title String containing the dimension of this worksheet
867
     * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
868
     *            be updated to reflect the new sheet name.
869
     *          This should be left as the default true, unless you are
870
     *          certain that no formula cells on any worksheet contain
871
     *          references to this worksheet
872
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
873
     *                       at parse time (by Readers), where titles can be assumed to be valid.
874
     *
875
     * @return $this
876
     */
877
    public function setTitle(string $title, bool $updateFormulaCellReferences = true, bool $validate = true): static
11,419✔
878
    {
879
        // Is this a 'rename' or not?
880
        if ($this->getTitle() == $title) {
11,419✔
881
            return $this;
338✔
882
        }
883

884
        // Old title
885
        $oldTitle = $this->getTitle();
11,419✔
886

887
        if ($validate) {
11,419✔
888
            // Syntax check
889
            self::checkSheetTitle($title);
11,419✔
890

891
            if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
11,419✔
892
                // Is there already such sheet name?
893
                if ($this->parent->sheetNameExists($title)) {
846✔
894
                    // Use name, but append with lowest possible integer
895

896
                    if (StringHelper::countCharacters($title) > 29) {
2✔
897
                        $title = StringHelper::substring($title, 0, 29);
×
898
                    }
899
                    $i = 1;
2✔
900
                    while ($this->parent->sheetNameExists($title . ' ' . $i)) {
2✔
901
                        ++$i;
1✔
902
                        if ($i == 10) {
1✔
903
                            if (StringHelper::countCharacters($title) > 28) {
×
904
                                $title = StringHelper::substring($title, 0, 28);
×
905
                            }
906
                        } elseif ($i == 100) {
1✔
907
                            if (StringHelper::countCharacters($title) > 27) {
×
908
                                $title = StringHelper::substring($title, 0, 27);
×
909
                            }
910
                        }
911
                    }
912

913
                    $title .= " $i";
2✔
914
                }
915
            }
916
        }
917

918
        // Set title
919
        $this->title = $title;
11,419✔
920

921
        if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
11,419✔
922
            // New title
923
            $newTitle = $this->getTitle();
1,510✔
924
            $this->parent->getCalculationEngine()
1,510✔
925
                ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
1,510✔
926
            if ($updateFormulaCellReferences) {
1,510✔
927
                ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle);
846✔
928
            }
929
        }
930

931
        return $this;
11,419✔
932
    }
933

934
    /**
935
     * Get sheet state.
936
     *
937
     * @return string Sheet state (visible, hidden, veryHidden)
938
     */
939
    public function getSheetState(): string
585✔
940
    {
941
        return $this->sheetState;
585✔
942
    }
943

944
    /**
945
     * Set sheet state.
946
     *
947
     * @param string $value Sheet state (visible, hidden, veryHidden)
948
     *
949
     * @return $this
950
     */
951
    public function setSheetState(string $value): static
11,419✔
952
    {
953
        $this->sheetState = $value;
11,419✔
954

955
        return $this;
11,419✔
956
    }
957

958
    /**
959
     * Get page setup.
960
     */
961
    public function getPageSetup(): PageSetup
1,767✔
962
    {
963
        return $this->pageSetup;
1,767✔
964
    }
965

966
    /**
967
     * Set page setup.
968
     *
969
     * @return $this
970
     */
971
    public function setPageSetup(PageSetup $pageSetup): static
1✔
972
    {
973
        $this->pageSetup = $pageSetup;
1✔
974

975
        return $this;
1✔
976
    }
977

978
    /**
979
     * Get page margins.
980
     */
981
    public function getPageMargins(): PageMargins
1,756✔
982
    {
983
        return $this->pageMargins;
1,756✔
984
    }
985

986
    /**
987
     * Set page margins.
988
     *
989
     * @return $this
990
     */
991
    public function setPageMargins(PageMargins $pageMargins): static
1✔
992
    {
993
        $this->pageMargins = $pageMargins;
1✔
994

995
        return $this;
1✔
996
    }
997

998
    /**
999
     * Get page header/footer.
1000
     */
1001
    public function getHeaderFooter(): HeaderFooter
649✔
1002
    {
1003
        return $this->headerFooter;
649✔
1004
    }
1005

1006
    /**
1007
     * Set page header/footer.
1008
     *
1009
     * @return $this
1010
     */
1011
    public function setHeaderFooter(HeaderFooter $headerFooter): static
1✔
1012
    {
1013
        $this->headerFooter = $headerFooter;
1✔
1014

1015
        return $this;
1✔
1016
    }
1017

1018
    /**
1019
     * Get sheet view.
1020
     */
1021
    public function getSheetView(): SheetView
680✔
1022
    {
1023
        return $this->sheetView;
680✔
1024
    }
1025

1026
    /**
1027
     * Set sheet view.
1028
     *
1029
     * @return $this
1030
     */
1031
    public function setSheetView(SheetView $sheetView): static
1✔
1032
    {
1033
        $this->sheetView = $sheetView;
1✔
1034

1035
        return $this;
1✔
1036
    }
1037

1038
    /**
1039
     * Get Protection.
1040
     */
1041
    public function getProtection(): Protection
699✔
1042
    {
1043
        return $this->protection;
699✔
1044
    }
1045

1046
    /**
1047
     * Set Protection.
1048
     *
1049
     * @return $this
1050
     */
1051
    public function setProtection(Protection $protection): static
1✔
1052
    {
1053
        $this->protection = $protection;
1✔
1054

1055
        return $this;
1✔
1056
    }
1057

1058
    /**
1059
     * Get highest worksheet column.
1060
     *
1061
     * @param null|int|string $row Return the data highest column for the specified row,
1062
     *                                     or the highest column of any row if no row number is passed
1063
     *
1064
     * @return string Highest column name
1065
     */
1066
    public function getHighestColumn($row = null): string
1,663✔
1067
    {
1068
        if ($row === null) {
1,663✔
1069
            return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
1,662✔
1070
        }
1071

1072
        return $this->getHighestDataColumn($row);
1✔
1073
    }
1074

1075
    /**
1076
     * Get highest worksheet column that contains data.
1077
     *
1078
     * @param null|int|string $row Return the highest data column for the specified row,
1079
     *                                     or the highest data column of any row if no row number is passed
1080
     *
1081
     * @return string Highest column name that contains data
1082
     */
1083
    public function getHighestDataColumn($row = null): string
906✔
1084
    {
1085
        return $this->cellCollection->getHighestColumn($row);
906✔
1086
    }
1087

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

1102
        return $this->getHighestDataRow($column);
1✔
1103
    }
1104

1105
    /**
1106
     * Get highest worksheet row that contains data.
1107
     *
1108
     * @param null|string $column Return the highest data row for the specified column,
1109
     *                                     or the highest data row of any column if no column letter is passed
1110
     *
1111
     * @return int Highest row number that contains data
1112
     */
1113
    public function getHighestDataRow(?string $column = null): int
810✔
1114
    {
1115
        return $this->cellCollection->getHighestRow($column);
810✔
1116
    }
1117

1118
    /**
1119
     * Get highest worksheet column and highest row that have cell records.
1120
     *
1121
     * @return array{row: int, column: string} Highest column name and highest row number
1122
     */
1123
    public function getHighestRowAndColumn(): array
1✔
1124
    {
1125
        return $this->cellCollection->getHighestRowAndColumn();
1✔
1126
    }
1127

1128
    /**
1129
     * Set a cell value.
1130
     *
1131
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1132
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1133
     * @param mixed $value Value for the cell
1134
     * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
1135
     *
1136
     * @return $this
1137
     */
1138
    public function setCellValue(CellAddress|string|array $coordinate, mixed $value, ?IValueBinder $binder = null): static
5,106✔
1139
    {
1140
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
5,106✔
1141
        $this->getCell($cellAddress)->setValue($value, $binder);
5,106✔
1142

1143
        return $this;
5,100✔
1144
    }
1145

1146
    /**
1147
     * Set a cell value.
1148
     *
1149
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1150
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1151
     * @param mixed $value Value of the cell
1152
     * @param string $dataType Explicit data type, see DataType::TYPE_*
1153
     *        Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
1154
     *             method, then it is your responsibility as an end-user developer to validate that the value and
1155
     *             the datatype match.
1156
     *       If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype
1157
     *          that you specify.
1158
     *
1159
     * @see DataType
1160
     *
1161
     * @return $this
1162
     */
1163
    public function setCellValueExplicit(CellAddress|string|array $coordinate, mixed $value, string $dataType): static
123✔
1164
    {
1165
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
123✔
1166
        $this->getCell($cellAddress)->setValueExplicit($value, $dataType);
123✔
1167

1168
        return $this;
123✔
1169
    }
1170

1171
    /**
1172
     * Get cell at a specific coordinate.
1173
     *
1174
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1175
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1176
     *
1177
     * @return Cell Cell that was found or created
1178
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1179
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1180
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1181
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1182
     *              the active cell has changed.
1183
     */
1184
    public function getCell(CellAddress|string|array $coordinate): Cell
10,921✔
1185
    {
1186
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
10,921✔
1187

1188
        // Shortcut for increased performance for the vast majority of simple cases
1189
        if ($this->cellCollection->has($cellAddress)) {
10,921✔
1190
            /** @var Cell $cell */
1191
            $cell = $this->cellCollection->get($cellAddress);
10,892✔
1192

1193
            return $cell;
10,892✔
1194
        }
1195

1196
        /** @var Worksheet $sheet */
1197
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
10,921✔
1198
        $cell = $sheet->getCellCollection()->get($finalCoordinate);
10,921✔
1199

1200
        return $cell ?? $sheet->createNewCell($finalCoordinate);
10,921✔
1201
    }
1202

1203
    /**
1204
     * Get the correct Worksheet and coordinate from a coordinate that may
1205
     * contains reference to another sheet or a named range.
1206
     *
1207
     * @return array{0: Worksheet, 1: string}
1208
     */
1209
    private function getWorksheetAndCoordinate(string $coordinate): array
10,945✔
1210
    {
1211
        $sheet = null;
10,945✔
1212
        $finalCoordinate = null;
10,945✔
1213

1214
        // Worksheet reference?
1215
        if (str_contains($coordinate, '!')) {
10,945✔
1216
            $worksheetReference = self::extractSheetTitle($coordinate, true, true);
×
1217

1218
            $sheet = $this->getParentOrThrow()->getSheetByName($worksheetReference[0]);
×
1219
            $finalCoordinate = strtoupper($worksheetReference[1]);
×
1220

1221
            if ($sheet === null) {
×
1222
                throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
×
1223
            }
1224
        } elseif (
1225
            !Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate)
10,945✔
1226
            && Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate)
10,945✔
1227
        ) {
1228
            // Named range?
1229
            $namedRange = $this->validateNamedRange($coordinate, true);
17✔
1230
            if ($namedRange !== null) {
17✔
1231
                $sheet = $namedRange->getWorksheet();
12✔
1232
                if ($sheet === null) {
12✔
1233
                    throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
×
1234
                }
1235

1236
                /** @phpstan-ignore-next-line */
1237
                $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
12✔
1238
                $finalCoordinate = str_replace('$', '', $cellCoordinate);
12✔
1239
            }
1240
        }
1241

1242
        if ($sheet === null || $finalCoordinate === null) {
10,945✔
1243
            $sheet = $this;
10,945✔
1244
            $finalCoordinate = strtoupper($coordinate);
10,945✔
1245
        }
1246

1247
        if (Coordinate::coordinateIsRange($finalCoordinate)) {
10,945✔
1248
            throw new Exception('Cell coordinate string can not be a range of cells.');
2✔
1249
        }
1250
        $finalCoordinate = str_replace('$', '', $finalCoordinate);
10,945✔
1251

1252
        return [$sheet, $finalCoordinate];
10,945✔
1253
    }
1254

1255
    /**
1256
     * Get an existing cell at a specific coordinate, or null.
1257
     *
1258
     * @param string $coordinate Coordinate of the cell, eg: 'A1'
1259
     *
1260
     * @return null|Cell Cell that was found or null
1261
     */
1262
    private function getCellOrNull(string $coordinate): ?Cell
67✔
1263
    {
1264
        // Check cell collection
1265
        if ($this->cellCollection->has($coordinate)) {
67✔
1266
            return $this->cellCollection->get($coordinate);
67✔
1267
        }
1268

1269
        return null;
×
1270
    }
1271

1272
    /**
1273
     * Create a new cell at the specified coordinate.
1274
     *
1275
     * @param string $coordinate Coordinate of the cell
1276
     *
1277
     * @return Cell Cell that was created
1278
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1279
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1280
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1281
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1282
     *              the active cell has changed.
1283
     */
1284
    public function createNewCell(string $coordinate): Cell
10,921✔
1285
    {
1286
        [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate);
10,921✔
1287
        $cell = new Cell(null, DataType::TYPE_NULL, $this);
10,921✔
1288
        $this->cellCollection->add($coordinate, $cell);
10,921✔
1289

1290
        // Coordinates
1291
        if ($column > $this->cachedHighestColumn) {
10,921✔
1292
            $this->cachedHighestColumn = $column;
7,510✔
1293
        }
1294
        if ($row > $this->cachedHighestRow) {
10,921✔
1295
            $this->cachedHighestRow = $row;
8,953✔
1296
        }
1297

1298
        // Cell needs appropriate xfIndex from dimensions records
1299
        //    but don't create dimension records if they don't already exist
1300
        $rowDimension = $this->rowDimensions[$row] ?? null;
10,921✔
1301
        $columnDimension = $this->columnDimensions[$columnString] ?? null;
10,921✔
1302

1303
        $xfSet = false;
10,921✔
1304
        if ($rowDimension !== null) {
10,921✔
1305
            $rowXf = (int) $rowDimension->getXfIndex();
419✔
1306
            if ($rowXf > 0) {
419✔
1307
                // then there is a row dimension with explicit style, assign it to the cell
1308
                $cell->setXfIndex($rowXf);
203✔
1309
                $xfSet = true;
203✔
1310
            }
1311
        }
1312
        if (!$xfSet && $columnDimension !== null) {
10,921✔
1313
            $colXf = (int) $columnDimension->getXfIndex();
602✔
1314
            if ($colXf > 0) {
602✔
1315
                // then there is a column dimension, assign it to the cell
1316
                $cell->setXfIndex($colXf);
229✔
1317
            }
1318
        }
1319

1320
        return $cell;
10,921✔
1321
    }
1322

1323
    /**
1324
     * Does the cell at a specific coordinate exist?
1325
     *
1326
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1327
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1328
     */
1329
    public function cellExists(CellAddress|string|array $coordinate): bool
10,857✔
1330
    {
1331
        $cellAddress = Validations::validateCellAddress($coordinate);
10,857✔
1332
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
10,857✔
1333

1334
        return $sheet->getCellCollection()->has($finalCoordinate);
10,857✔
1335
    }
1336

1337
    /**
1338
     * Get row dimension at a specific row.
1339
     *
1340
     * @param int $row Numeric index of the row
1341
     */
1342
    public function getRowDimension(int $row): RowDimension
627✔
1343
    {
1344
        // Get row dimension
1345
        if (!isset($this->rowDimensions[$row])) {
627✔
1346
            $this->rowDimensions[$row] = new RowDimension($row);
627✔
1347

1348
            $this->cachedHighestRow = max($this->cachedHighestRow, $row);
627✔
1349
        }
1350

1351
        return $this->rowDimensions[$row];
627✔
1352
    }
1353

1354
    public function getRowStyle(int $row): ?Style
1✔
1355
    {
1356
        return $this->parent?->getCellXfByIndexOrNull(
1✔
1357
            ($this->rowDimensions[$row] ?? null)?->getXfIndex()
1✔
1358
        );
1✔
1359
    }
1360

1361
    public function rowDimensionExists(int $row): bool
705✔
1362
    {
1363
        return isset($this->rowDimensions[$row]);
705✔
1364
    }
1365

1366
    public function columnDimensionExists(string $column): bool
107✔
1367
    {
1368
        return isset($this->columnDimensions[$column]);
107✔
1369
    }
1370

1371
    /**
1372
     * Get column dimension at a specific column.
1373
     *
1374
     * @param string $column String index of the column eg: 'A'
1375
     */
1376
    public function getColumnDimension(string $column): ColumnDimension
706✔
1377
    {
1378
        // Uppercase coordinate
1379
        $column = strtoupper($column);
706✔
1380

1381
        // Fetch dimensions
1382
        if (!isset($this->columnDimensions[$column])) {
706✔
1383
            $this->columnDimensions[$column] = new ColumnDimension($column);
706✔
1384

1385
            $columnIndex = Coordinate::columnIndexFromString($column);
706✔
1386
            if ($this->cachedHighestColumn < $columnIndex) {
706✔
1387
                $this->cachedHighestColumn = $columnIndex;
488✔
1388
            }
1389
        }
1390

1391
        return $this->columnDimensions[$column];
706✔
1392
    }
1393

1394
    /**
1395
     * Get column dimension at a specific column by using numeric cell coordinates.
1396
     *
1397
     * @param int $columnIndex Numeric column coordinate of the cell
1398
     */
1399
    public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
136✔
1400
    {
1401
        return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
136✔
1402
    }
1403

1404
    public function getColumnStyle(string $column): ?Style
1✔
1405
    {
1406
        return $this->parent?->getCellXfByIndexOrNull(
1✔
1407
            ($this->columnDimensions[$column] ?? null)?->getXfIndex()
1✔
1408
        );
1✔
1409
    }
1410

1411
    /**
1412
     * Get style for cell.
1413
     *
1414
     * @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
1415
     *              A simple string containing a cell address like 'A1' or a cell range like 'A1:E10'
1416
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1417
     *              or a CellAddress or AddressRange object.
1418
     */
1419
    public function getStyle(AddressRange|CellAddress|int|string|array $cellCoordinate): Style
10,884✔
1420
    {
1421
        if (is_string($cellCoordinate)) {
10,884✔
1422
            $cellCoordinate = Validations::definedNameToCoordinate($cellCoordinate, $this);
10,882✔
1423
        }
1424
        $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate);
10,884✔
1425
        $cellCoordinate = str_replace('$', '', $cellCoordinate);
10,884✔
1426

1427
        // set this sheet as active
1428
        $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this));
10,884✔
1429

1430
        // set cell coordinate as active
1431
        $this->setSelectedCells($cellCoordinate);
10,884✔
1432

1433
        return $this->getParentOrThrow()->getCellXfSupervisor();
10,884✔
1434
    }
1435

1436
    /**
1437
     * Get table styles set for the for given cell.
1438
     *
1439
     * @param Cell $cell
1440
     *              The Cell for which the tables are retrieved
1441
     *
1442
     * @return Table[]
1443
     */
1444
    public function getTablesWithStylesForCell(Cell $cell): array
7✔
1445
    {
1446
        $retVal = [];
7✔
1447

1448
        foreach ($this->tableCollection as $table) {
7✔
1449
            $dxfsTableStyle = $table->getStyle()->getTableDxfsStyle();
7✔
1450
            if ($dxfsTableStyle !== null) {
7✔
1451
                if ($dxfsTableStyle->getHeaderRowStyle() !== null || $dxfsTableStyle->getFirstRowStripeStyle() !== null || $dxfsTableStyle->getSecondRowStripeStyle() !== null) {
4✔
1452
                    $range = $table->getRange();
4✔
1453
                    if ($cell->isInRange($range)) {
4✔
1454
                        $retVal[] = $table;
4✔
1455
                    }
1456
                }
1457
            }
1458
        }
1459

1460
        return $retVal;
7✔
1461
    }
1462

1463
    /**
1464
     * Get tables without styles set for the for given cell.
1465
     *
1466
     * @param Cell $cell
1467
     *              The Cell for which the tables are retrieved
1468
     *
1469
     * @return Table[]
1470
     */
1471
    public function getTablesWithoutStylesForCell(Cell $cell): array
6✔
1472
    {
1473
        $retVal = [];
6✔
1474

1475
        foreach ($this->tableCollection as $table) {
6✔
1476
            $range = $table->getRange();
6✔
1477
            if ($cell->isInRange($range)) {
6✔
1478
                $dxfsTableStyle = $table->getStyle()->getTableDxfsStyle();
6✔
1479
                if ($dxfsTableStyle === null || ($dxfsTableStyle->getHeaderRowStyle() === null && $dxfsTableStyle->getFirstRowStripeStyle() === null && $dxfsTableStyle->getSecondRowStripeStyle() === null)) {
6✔
1480
                    $retVal[] = $table;
2✔
1481
                }
1482
            }
1483
        }
1484

1485
        return $retVal;
6✔
1486
    }
1487

1488
    /**
1489
     * Get conditional styles for a cell.
1490
     *
1491
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1492
     *          If a single cell is referenced, then the array of conditional styles will be returned if the cell is
1493
     *               included in a conditional style range.
1494
     *          If a range of cells is specified, then the styles will only be returned if the range matches the entire
1495
     *               range of the conditional.
1496
     * @param bool $firstOnly default true, return all matching
1497
     *          conditionals ordered by priority if false, first only if true
1498
     *
1499
     * @return Conditional[]
1500
     */
1501
    public function getConditionalStyles(string $coordinate, bool $firstOnly = true): array
833✔
1502
    {
1503
        $coordinate = strtoupper($coordinate);
833✔
1504
        if (Preg::isMatch('/[: ,]/', $coordinate)) {
833✔
1505
            return $this->conditionalStylesCollection[$coordinate] ?? [];
49✔
1506
        }
1507

1508
        $conditionalStyles = [];
809✔
1509
        foreach ($this->conditionalStylesCollection as $keyStylesOrig => $conditionalRange) {
809✔
1510
            $keyStyles = Coordinate::resolveUnionAndIntersection($keyStylesOrig);
225✔
1511
            $keyParts = explode(',', $keyStyles);
225✔
1512
            foreach ($keyParts as $keyPart) {
225✔
1513
                if ($keyPart === $coordinate) {
225✔
1514
                    if ($firstOnly) {
14✔
1515
                        return $conditionalRange;
14✔
1516
                    }
1517
                    $conditionalStyles[$keyStylesOrig] = $conditionalRange;
×
1518

1519
                    break;
×
1520
                } elseif (str_contains($keyPart, ':')) {
220✔
1521
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
215✔
1522
                        if ($firstOnly) {
201✔
1523
                            return $conditionalRange;
200✔
1524
                        }
1525
                        $conditionalStyles[$keyStylesOrig] = $conditionalRange;
1✔
1526

1527
                        break;
1✔
1528
                    }
1529
                }
1530
            }
1531
        }
1532
        $outArray = [];
632✔
1533
        foreach ($conditionalStyles as $conditionalArray) {
632✔
1534
            foreach ($conditionalArray as $conditional) {
1✔
1535
                $outArray[] = $conditional;
1✔
1536
            }
1537
        }
1538
        usort($outArray, [self::class, 'comparePriority']);
632✔
1539

1540
        return $outArray;
632✔
1541
    }
1542

1543
    private static function comparePriority(Conditional $condA, Conditional $condB): int
1✔
1544
    {
1545
        $a = $condA->getPriority();
1✔
1546
        $b = $condB->getPriority();
1✔
1547
        if ($a === $b) {
1✔
1548
            return 0;
×
1549
        }
1550
        if ($a === 0) {
1✔
1551
            return 1;
×
1552
        }
1553
        if ($b === 0) {
1✔
1554
            return -1;
×
1555
        }
1556

1557
        return ($a < $b) ? -1 : 1;
1✔
1558
    }
1559

1560
    public function getConditionalRange(string $coordinate): ?string
192✔
1561
    {
1562
        $coordinate = strtoupper($coordinate);
192✔
1563
        $cell = $this->getCell($coordinate);
192✔
1564
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
192✔
1565
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
192✔
1566
            foreach ($cellBlocks as $cellBlock) {
192✔
1567
                if ($cell->isInRange($cellBlock)) {
192✔
1568
                    return $conditionalRange;
191✔
1569
                }
1570
            }
1571
        }
1572

1573
        return null;
10✔
1574
    }
1575

1576
    /**
1577
     * Do conditional styles exist for this cell?
1578
     *
1579
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1580
     *          If a single cell is specified, then this method will return true if that cell is included in a
1581
     *               conditional style range.
1582
     *          If a range of cells is specified, then true will only be returned if the range matches the entire
1583
     *               range of the conditional.
1584
     */
1585
    public function conditionalStylesExists(string $coordinate): bool
22✔
1586
    {
1587
        return !empty($this->getConditionalStyles($coordinate));
22✔
1588
    }
1589

1590
    /**
1591
     * Removes conditional styles for a cell.
1592
     *
1593
     * @param string $coordinate eg: 'A1'
1594
     *
1595
     * @return $this
1596
     */
1597
    public function removeConditionalStyles(string $coordinate): static
55✔
1598
    {
1599
        unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
55✔
1600

1601
        return $this;
55✔
1602
    }
1603

1604
    /**
1605
     * Get collection of conditional styles.
1606
     *
1607
     * @return Conditional[][]
1608
     */
1609
    public function getConditionalStylesCollection(): array
1,450✔
1610
    {
1611
        return $this->conditionalStylesCollection;
1,450✔
1612
    }
1613

1614
    /**
1615
     * Set conditional styles.
1616
     *
1617
     * @param string $coordinate eg: 'A1'
1618
     * @param Conditional[] $styles
1619
     *
1620
     * @return $this
1621
     */
1622
    public function setConditionalStyles(string $coordinate, array $styles): static
348✔
1623
    {
1624
        $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
348✔
1625

1626
        return $this;
348✔
1627
    }
1628

1629
    /**
1630
     * Duplicate cell style to a range of cells.
1631
     *
1632
     * Please note that this will overwrite existing cell styles for cells in range!
1633
     *
1634
     * @param Style $style 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 duplicateStyle(Style $style, string $range): static
2✔
1640
    {
1641
        // Add the style to the workbook if necessary
1642
        $workbook = $this->getParentOrThrow();
2✔
1643
        if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) {
2✔
1644
            // there is already such cell Xf in our collection
1645
            $xfIndex = $existingStyle->getIndex();
1✔
1646
        } else {
1647
            // we don't have such a cell Xf, need to add
1648
            $workbook->addCellXf($style);
2✔
1649
            $xfIndex = $style->getIndex();
2✔
1650
        }
1651

1652
        // Calculate range outer borders
1653
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
2✔
1654

1655
        // Make sure we can loop upwards on rows and columns
1656
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
2✔
1657
            $tmp = $rangeStart;
×
1658
            $rangeStart = $rangeEnd;
×
1659
            $rangeEnd = $tmp;
×
1660
        }
1661

1662
        // Loop through cells and apply styles
1663
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
2✔
1664
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
2✔
1665
                $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
2✔
1666
            }
1667
        }
1668

1669
        return $this;
2✔
1670
    }
1671

1672
    /**
1673
     * Duplicate conditional style to a range of cells.
1674
     *
1675
     * Please note that this will overwrite existing cell styles for cells in range!
1676
     *
1677
     * @param Conditional[] $styles Cell style to duplicate
1678
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1679
     *
1680
     * @return $this
1681
     */
1682
    public function duplicateConditionalStyle(array $styles, string $range = ''): static
18✔
1683
    {
1684
        foreach ($styles as $cellStyle) {
18✔
1685
            if (!($cellStyle instanceof Conditional)) { // @phpstan-ignore-line
18✔
1686
                throw new Exception('Style is not a conditional style');
×
1687
            }
1688
        }
1689

1690
        // Calculate range outer borders
1691
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
18✔
1692

1693
        // Make sure we can loop upwards on rows and columns
1694
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
18✔
1695
            $tmp = $rangeStart;
×
1696
            $rangeStart = $rangeEnd;
×
1697
            $rangeEnd = $tmp;
×
1698
        }
1699

1700
        // Loop through cells and apply styles
1701
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
18✔
1702
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
18✔
1703
                $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
18✔
1704
            }
1705
        }
1706

1707
        return $this;
18✔
1708
    }
1709

1710
    /**
1711
     * Set break on a cell.
1712
     *
1713
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1714
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1715
     * @param int $break Break type (type of Worksheet::BREAK_*)
1716
     *
1717
     * @return $this
1718
     */
1719
    public function setBreak(CellAddress|string|array $coordinate, int $break, int $max = -1): static
33✔
1720
    {
1721
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
33✔
1722

1723
        if ($break === self::BREAK_NONE) {
33✔
1724
            unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]);
7✔
1725
        } elseif ($break === self::BREAK_ROW) {
33✔
1726
            $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
23✔
1727
        } elseif ($break === self::BREAK_COLUMN) {
19✔
1728
            $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
19✔
1729
        }
1730

1731
        return $this;
33✔
1732
    }
1733

1734
    /**
1735
     * Get breaks.
1736
     *
1737
     * @return int[]
1738
     */
1739
    public function getBreaks(): array
717✔
1740
    {
1741
        $breaks = [];
717✔
1742
        /** @var callable $compareFunction */
1743
        $compareFunction = [self::class, 'compareRowBreaks'];
717✔
1744
        uksort($this->rowBreaks, $compareFunction);
717✔
1745
        foreach ($this->rowBreaks as $break) {
717✔
1746
            $breaks[$break->getCoordinate()] = self::BREAK_ROW;
10✔
1747
        }
1748
        /** @var callable $compareFunction */
1749
        $compareFunction = [self::class, 'compareColumnBreaks'];
717✔
1750
        uksort($this->columnBreaks, $compareFunction);
717✔
1751
        foreach ($this->columnBreaks as $break) {
717✔
1752
            $breaks[$break->getCoordinate()] = self::BREAK_COLUMN;
8✔
1753
        }
1754

1755
        return $breaks;
717✔
1756
    }
1757

1758
    /**
1759
     * Get row breaks.
1760
     *
1761
     * @return PageBreak[]
1762
     */
1763
    public function getRowBreaks(): array
593✔
1764
    {
1765
        /** @var callable $compareFunction */
1766
        $compareFunction = [self::class, 'compareRowBreaks'];
593✔
1767
        uksort($this->rowBreaks, $compareFunction);
593✔
1768

1769
        return $this->rowBreaks;
593✔
1770
    }
1771

1772
    protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int
9✔
1773
    {
1774
        $row1 = Coordinate::indexesFromString($coordinate1)[1];
9✔
1775
        $row2 = Coordinate::indexesFromString($coordinate2)[1];
9✔
1776

1777
        return $row1 - $row2;
9✔
1778
    }
1779

1780
    protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int
5✔
1781
    {
1782
        $column1 = Coordinate::indexesFromString($coordinate1)[0];
5✔
1783
        $column2 = Coordinate::indexesFromString($coordinate2)[0];
5✔
1784

1785
        return $column1 - $column2;
5✔
1786
    }
1787

1788
    /**
1789
     * Get column breaks.
1790
     *
1791
     * @return PageBreak[]
1792
     */
1793
    public function getColumnBreaks(): array
592✔
1794
    {
1795
        /** @var callable $compareFunction */
1796
        $compareFunction = [self::class, 'compareColumnBreaks'];
592✔
1797
        uksort($this->columnBreaks, $compareFunction);
592✔
1798

1799
        return $this->columnBreaks;
592✔
1800
    }
1801

1802
    /**
1803
     * Set merge on a cell range.
1804
     *
1805
     * @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'
1806
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1807
     *              or an AddressRange.
1808
     * @param string $behaviour How the merged cells should behave.
1809
     *               Possible values are:
1810
     *                   MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells
1811
     *                   MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells
1812
     *                   MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell
1813
     *
1814
     * @return $this
1815
     */
1816
    public function mergeCells(AddressRange|string|array $range, string $behaviour = self::MERGE_CELL_CONTENT_EMPTY): static
181✔
1817
    {
1818
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
181✔
1819

1820
        if (!str_contains($range, ':')) {
180✔
1821
            $range .= ":{$range}";
1✔
1822
        }
1823

1824
        if (!Preg::isMatch('/^([A-Z]+)(\d+):([A-Z]+)(\d+)$/', $range, $matches)) {
180✔
1825
            throw new Exception('Merge must be on a valid range of cells.');
1✔
1826
        }
1827

1828
        $this->mergeCells[$range] = $range;
179✔
1829
        $firstRow = (int) $matches[2];
179✔
1830
        $lastRow = (int) $matches[4];
179✔
1831
        $firstColumn = $matches[1];
179✔
1832
        $lastColumn = $matches[3];
179✔
1833
        $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn);
179✔
1834
        $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn);
179✔
1835
        $numberRows = $lastRow - $firstRow;
179✔
1836
        $numberColumns = $lastColumnIndex - $firstColumnIndex;
179✔
1837

1838
        if ($numberRows === 1 && $numberColumns === 1) {
179✔
1839
            return $this;
36✔
1840
        }
1841

1842
        // create upper left cell if it does not already exist
1843
        $upperLeft = "{$firstColumn}{$firstRow}";
172✔
1844
        if (!$this->cellExists($upperLeft)) {
172✔
1845
            $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
37✔
1846
        }
1847

1848
        if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) {
172✔
1849
            // Blank out the rest of the cells in the range (if they exist)
1850
            if ($numberRows > $numberColumns) {
61✔
1851
                $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour);
20✔
1852
            } else {
1853
                $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour);
41✔
1854
            }
1855
        }
1856

1857
        return $this;
172✔
1858
    }
1859

1860
    private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
20✔
1861
    {
1862
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
20✔
1863
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1✔
1864
            : [];
19✔
1865

1866
        foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) {
20✔
1867
            $iterator = $column->getCellIterator($firstRow);
20✔
1868
            $iterator->setIterateOnlyExistingCells(true);
20✔
1869
            foreach ($iterator as $cell) {
20✔
1870
                $row = $cell->getRow();
20✔
1871
                if ($row > $lastRow) {
20✔
1872
                    break;
8✔
1873
                }
1874
                $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
20✔
1875
            }
1876
        }
1877

1878
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
20✔
1879
            /** @var string[] $leftCellValue */
1880
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1✔
1881
        }
1882
    }
1883

1884
    private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
41✔
1885
    {
1886
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
41✔
1887
            ? [$this->getCell($upperLeft)->getFormattedValue()]
4✔
1888
            : [];
37✔
1889

1890
        foreach ($this->getRowIterator($firstRow, $lastRow) as $row) {
41✔
1891
            $iterator = $row->getCellIterator($firstColumn);
41✔
1892
            $iterator->setIterateOnlyExistingCells(true);
41✔
1893
            foreach ($iterator as $cell) {
41✔
1894
                $column = $cell->getColumn();
41✔
1895
                $columnIndex = Coordinate::columnIndexFromString($column);
41✔
1896
                if ($columnIndex > $lastColumnIndex) {
41✔
1897
                    break;
9✔
1898
                }
1899
                $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
41✔
1900
            }
1901
        }
1902

1903
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
41✔
1904
            /** @var string[] $leftCellValue */
1905
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
4✔
1906
        }
1907
    }
1908

1909
    /**
1910
     * @param mixed[] $leftCellValue
1911
     *
1912
     * @return mixed[]
1913
     */
1914
    public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array
61✔
1915
    {
1916
        if ($cell->getCoordinate() !== $upperLeft) {
61✔
1917
            Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance();
25✔
1918
            if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
25✔
1919
                $cellValue = $cell->getFormattedValue();
5✔
1920
                if ($cellValue !== '') {
5✔
1921
                    $leftCellValue[] = $cellValue;
5✔
1922
                }
1923
            }
1924
            $cell->setValueExplicit(null, DataType::TYPE_NULL);
25✔
1925
        }
1926

1927
        return $leftCellValue;
61✔
1928
    }
1929

1930
    /**
1931
     * Remove merge on a cell range.
1932
     *
1933
     * @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'
1934
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1935
     *              or an AddressRange.
1936
     *
1937
     * @return $this
1938
     */
1939
    public function unmergeCells(AddressRange|string|array $range): static
23✔
1940
    {
1941
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
23✔
1942

1943
        if (str_contains($range, ':')) {
23✔
1944
            if (isset($this->mergeCells[$range])) {
22✔
1945
                unset($this->mergeCells[$range]);
22✔
1946
            } else {
UNCOV
1947
                throw new Exception('Cell range ' . $range . ' not known as merged.');
×
1948
            }
1949
        } else {
1950
            throw new Exception('Merge can only be removed from a range of cells.');
1✔
1951
        }
1952

1953
        return $this;
22✔
1954
    }
1955

1956
    /**
1957
     * Get merge cells array.
1958
     *
1959
     * @return string[]
1960
     */
1961
    public function getMergeCells(): array
1,352✔
1962
    {
1963
        return $this->mergeCells;
1,352✔
1964
    }
1965

1966
    /**
1967
     * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
1968
     * a single cell range.
1969
     *
1970
     * @param string[] $mergeCells
1971
     *
1972
     * @return $this
1973
     */
1974
    public function setMergeCells(array $mergeCells): static
127✔
1975
    {
1976
        $this->mergeCells = $mergeCells;
127✔
1977

1978
        return $this;
127✔
1979
    }
1980

1981
    /**
1982
     * Set protection on a cell or cell range.
1983
     *
1984
     * @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'
1985
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1986
     *              or a CellAddress or AddressRange object.
1987
     * @param string $password Password to unlock the protection
1988
     * @param bool $alreadyHashed If the password has already been hashed, set this to true
1989
     *
1990
     * @return $this
1991
     */
1992
    public function protectCells(AddressRange|CellAddress|int|string|array $range, string $password = '', bool $alreadyHashed = false, string $name = '', string $securityDescriptor = ''): static
28✔
1993
    {
1994
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
28✔
1995

1996
        if (!$alreadyHashed && $password !== '') {
28✔
1997
            $password = Shared\PasswordHasher::hashPassword($password);
24✔
1998
        }
1999
        $this->protectedCells[$range] = new ProtectedRange($range, $password, $name, $securityDescriptor);
28✔
2000

2001
        return $this;
28✔
2002
    }
2003

2004
    /**
2005
     * Remove protection on a cell or cell range.
2006
     *
2007
     * @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'
2008
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2009
     *              or a CellAddress or AddressRange object.
2010
     *
2011
     * @return $this
2012
     */
2013
    public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static
22✔
2014
    {
2015
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
22✔
2016

2017
        if (isset($this->protectedCells[$range])) {
22✔
2018
            unset($this->protectedCells[$range]);
21✔
2019
        } else {
2020
            throw new Exception('Cell range ' . $range . ' not known as protected.');
1✔
2021
        }
2022

2023
        return $this;
21✔
2024
    }
2025

2026
    /**
2027
     * Get protected cells.
2028
     *
2029
     * @return ProtectedRange[]
2030
     */
2031
    public function getProtectedCellRanges(): array
703✔
2032
    {
2033
        return $this->protectedCells;
703✔
2034
    }
2035

2036
    /**
2037
     * Get Autofilter.
2038
     */
2039
    public function getAutoFilter(): AutoFilter
921✔
2040
    {
2041
        return $this->autoFilter;
921✔
2042
    }
2043

2044
    /**
2045
     * Set AutoFilter.
2046
     *
2047
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|AutoFilter|string $autoFilterOrRange
2048
     *            A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
2049
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2050
     *              or an AddressRange.
2051
     *
2052
     * @return $this
2053
     */
2054
    public function setAutoFilter(AddressRange|string|array|AutoFilter $autoFilterOrRange): static
21✔
2055
    {
2056
        if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
21✔
UNCOV
2057
            $this->autoFilter = $autoFilterOrRange;
×
2058
        } else {
2059
            $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange));
21✔
2060

2061
            $this->autoFilter->setRange($cellRange);
21✔
2062
        }
2063

2064
        return $this;
21✔
2065
    }
2066

2067
    /**
2068
     * Remove autofilter.
2069
     */
2070
    public function removeAutoFilter(): self
1✔
2071
    {
2072
        $this->autoFilter->setRange('');
1✔
2073

2074
        return $this;
1✔
2075
    }
2076

2077
    /**
2078
     * Get collection of Tables.
2079
     *
2080
     * @return ArrayObject<int, Table>
2081
     */
2082
    public function getTableCollection(): ArrayObject
10,915✔
2083
    {
2084
        return $this->tableCollection;
10,915✔
2085
    }
2086

2087
    /**
2088
     * Add Table.
2089
     *
2090
     * @return $this
2091
     */
2092
    public function addTable(Table $table): self
105✔
2093
    {
2094
        $table->setWorksheet($this);
105✔
2095
        $this->tableCollection[] = $table;
105✔
2096

2097
        return $this;
105✔
2098
    }
2099

2100
    /**
2101
     * @return string[] array of Table names
2102
     */
2103
    public function getTableNames(): array
1✔
2104
    {
2105
        $tableNames = [];
1✔
2106

2107
        foreach ($this->tableCollection as $table) {
1✔
2108
            /** @var Table $table */
2109
            $tableNames[] = $table->getName();
1✔
2110
        }
2111

2112
        return $tableNames;
1✔
2113
    }
2114

2115
    /**
2116
     * @param string $name the table name to search
2117
     *
2118
     * @return null|Table The table from the tables collection, or null if not found
2119
     */
2120
    public function getTableByName(string $name): ?Table
97✔
2121
    {
2122
        $tableIndex = $this->getTableIndexByName($name);
97✔
2123

2124
        return ($tableIndex === null) ? null : $this->tableCollection[$tableIndex];
97✔
2125
    }
2126

2127
    /**
2128
     * @param string $name the table name to search
2129
     *
2130
     * @return null|int The index of the located table in the tables collection, or null if not found
2131
     */
2132
    protected function getTableIndexByName(string $name): ?int
98✔
2133
    {
2134
        $name = StringHelper::strToUpper($name);
98✔
2135
        foreach ($this->tableCollection as $index => $table) {
98✔
2136
            /** @var Table $table */
2137
            if (StringHelper::strToUpper($table->getName()) === $name) {
63✔
2138
                return $index;
62✔
2139
            }
2140
        }
2141

2142
        return null;
41✔
2143
    }
2144

2145
    /**
2146
     * Remove Table by name.
2147
     *
2148
     * @param string $name Table name
2149
     *
2150
     * @return $this
2151
     */
2152
    public function removeTableByName(string $name): self
1✔
2153
    {
2154
        $tableIndex = $this->getTableIndexByName($name);
1✔
2155

2156
        if ($tableIndex !== null) {
1✔
2157
            unset($this->tableCollection[$tableIndex]);
1✔
2158
        }
2159

2160
        return $this;
1✔
2161
    }
2162

2163
    /**
2164
     * Remove collection of Tables.
2165
     */
2166
    public function removeTableCollection(): self
1✔
2167
    {
2168
        $this->tableCollection = new ArrayObject();
1✔
2169

2170
        return $this;
1✔
2171
    }
2172

2173
    /**
2174
     * Get Freeze Pane.
2175
     */
2176
    public function getFreezePane(): ?string
317✔
2177
    {
2178
        return $this->freezePane;
317✔
2179
    }
2180

2181
    /**
2182
     * Freeze Pane.
2183
     *
2184
     * Examples:
2185
     *
2186
     *     - A2 will freeze the rows above cell A2 (i.e row 1)
2187
     *     - B1 will freeze the columns to the left of cell B1 (i.e column A)
2188
     *     - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
2189
     *
2190
     * @param null|array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
2191
     *            or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2192
     *        Passing a null value for this argument will clear any existing freeze pane for this worksheet.
2193
     * @param null|array{0: int, 1: int}|CellAddress|string $topLeftCell default position of the right bottom pane
2194
     *            Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]),
2195
     *            or a CellAddress object.
2196
     *
2197
     * @return $this
2198
     */
2199
    public function freezePane(null|CellAddress|string|array $coordinate, null|CellAddress|string|array $topLeftCell = null, bool $frozenSplit = false): static
50✔
2200
    {
2201
        $this->panes = [
50✔
2202
            'bottomRight' => null,
50✔
2203
            'bottomLeft' => null,
50✔
2204
            'topRight' => null,
50✔
2205
            'topLeft' => null,
50✔
2206
        ];
50✔
2207
        $cellAddress = ($coordinate !== null)
50✔
2208
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate))
50✔
2209
            : null;
1✔
2210
        if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) {
50✔
2211
            throw new Exception('Freeze pane can not be set on a range of cells.');
1✔
2212
        }
2213
        $topLeftCell = ($topLeftCell !== null)
49✔
2214
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell))
37✔
2215
            : null;
37✔
2216

2217
        if ($cellAddress !== null && $topLeftCell === null) {
49✔
2218
            $coordinate = Coordinate::coordinateFromString($cellAddress);
37✔
2219
            $topLeftCell = $coordinate[0] . $coordinate[1];
37✔
2220
        }
2221

2222
        $topLeftCell = "$topLeftCell";
49✔
2223
        $this->paneTopLeftCell = $topLeftCell;
49✔
2224

2225
        $this->freezePane = $cellAddress;
49✔
2226
        $this->topLeftCell = $topLeftCell;
49✔
2227
        if ($cellAddress === null) {
49✔
2228
            $this->paneState = '';
1✔
2229
            $this->xSplit = $this->ySplit = 0;
1✔
2230
            $this->activePane = '';
1✔
2231
        } else {
2232
            $coordinates = Coordinate::indexesFromString($cellAddress);
49✔
2233
            $this->xSplit = $coordinates[0] - 1;
49✔
2234
            $this->ySplit = $coordinates[1] - 1;
49✔
2235
            if ($this->xSplit > 0 || $this->ySplit > 0) {
49✔
2236
                $this->paneState = $frozenSplit ? self::PANE_FROZENSPLIT : self::PANE_FROZEN;
48✔
2237
                $this->setSelectedCellsActivePane();
48✔
2238
            } else {
2239
                $this->paneState = '';
1✔
2240
                $this->freezePane = null;
1✔
2241
                $this->activePane = '';
1✔
2242
            }
2243
        }
2244

2245
        return $this;
49✔
2246
    }
2247

2248
    public function setTopLeftCell(string $topLeftCell): self
61✔
2249
    {
2250
        $this->topLeftCell = $topLeftCell;
61✔
2251

2252
        return $this;
61✔
2253
    }
2254

2255
    /**
2256
     * Unfreeze Pane.
2257
     *
2258
     * @return $this
2259
     */
2260
    public function unfreezePane(): static
1✔
2261
    {
2262
        return $this->freezePane(null);
1✔
2263
    }
2264

2265
    /**
2266
     * Get the default position of the right bottom pane.
2267
     */
2268
    public function getTopLeftCell(): ?string
525✔
2269
    {
2270
        return $this->topLeftCell;
525✔
2271
    }
2272

2273
    public function getPaneTopLeftCell(): string
11✔
2274
    {
2275
        return $this->paneTopLeftCell;
11✔
2276
    }
2277

2278
    public function setPaneTopLeftCell(string $paneTopLeftCell): self
26✔
2279
    {
2280
        $this->paneTopLeftCell = $paneTopLeftCell;
26✔
2281

2282
        return $this;
26✔
2283
    }
2284

2285
    public function usesPanes(): bool
513✔
2286
    {
2287
        return $this->xSplit > 0 || $this->ySplit > 0;
513✔
2288
    }
2289

2290
    public function getPane(string $position): ?Pane
2✔
2291
    {
2292
        return $this->panes[$position] ?? null;
2✔
2293
    }
2294

2295
    public function setPane(string $position, ?Pane $pane): self
47✔
2296
    {
2297
        if (array_key_exists($position, $this->panes)) {
47✔
2298
            $this->panes[$position] = $pane;
47✔
2299
        }
2300

2301
        return $this;
47✔
2302
    }
2303

2304
    /** @return (null|Pane)[] */
2305
    public function getPanes(): array
3✔
2306
    {
2307
        return $this->panes;
3✔
2308
    }
2309

2310
    public function getActivePane(): string
14✔
2311
    {
2312
        return $this->activePane;
14✔
2313
    }
2314

2315
    public function setActivePane(string $activePane): self
49✔
2316
    {
2317
        $this->activePane = array_key_exists($activePane, $this->panes) ? $activePane : '';
49✔
2318

2319
        return $this;
49✔
2320
    }
2321

2322
    public function getXSplit(): int
11✔
2323
    {
2324
        return $this->xSplit;
11✔
2325
    }
2326

2327
    public function setXSplit(int $xSplit): self
11✔
2328
    {
2329
        $this->xSplit = $xSplit;
11✔
2330
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
11✔
2331
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
1✔
2332
        }
2333

2334
        return $this;
11✔
2335
    }
2336

2337
    public function getYSplit(): int
11✔
2338
    {
2339
        return $this->ySplit;
11✔
2340
    }
2341

2342
    public function setYSplit(int $ySplit): self
26✔
2343
    {
2344
        $this->ySplit = $ySplit;
26✔
2345
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
26✔
2346
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
1✔
2347
        }
2348

2349
        return $this;
26✔
2350
    }
2351

2352
    public function getPaneState(): string
30✔
2353
    {
2354
        return $this->paneState;
30✔
2355
    }
2356

2357
    public const PANE_FROZEN = 'frozen';
2358
    public const PANE_FROZENSPLIT = 'frozenSplit';
2359
    public const PANE_SPLIT = 'split';
2360
    private const VALIDPANESTATE = [self::PANE_FROZEN, self::PANE_SPLIT, self::PANE_FROZENSPLIT];
2361
    private const VALIDFROZENSTATE = [self::PANE_FROZEN, self::PANE_FROZENSPLIT];
2362

2363
    public function setPaneState(string $paneState): self
26✔
2364
    {
2365
        $this->paneState = in_array($paneState, self::VALIDPANESTATE, true) ? $paneState : '';
26✔
2366
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
26✔
2367
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
25✔
2368
        } else {
2369
            $this->freezePane = null;
3✔
2370
        }
2371

2372
        return $this;
26✔
2373
    }
2374

2375
    /**
2376
     * Insert a new row, updating all possible related data.
2377
     *
2378
     * @param int $before Insert before this row number
2379
     * @param int $numberOfRows Number of new rows to insert
2380
     *
2381
     * @return $this
2382
     */
2383
    public function insertNewRowBefore(int $before, int $numberOfRows = 1): static
43✔
2384
    {
2385
        if ($before >= 1) {
43✔
2386
            $objReferenceHelper = ReferenceHelper::getInstance();
42✔
2387
            $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
42✔
2388
        } else {
2389
            throw new Exception('Rows can only be inserted before at least row 1.');
1✔
2390
        }
2391

2392
        return $this;
42✔
2393
    }
2394

2395
    /**
2396
     * Insert a new column, updating all possible related data.
2397
     *
2398
     * @param string $before Insert before this column Name, eg: 'A'
2399
     * @param int $numberOfColumns Number of new columns to insert
2400
     *
2401
     * @return $this
2402
     */
2403
    public function insertNewColumnBefore(string $before, int $numberOfColumns = 1): static
51✔
2404
    {
2405
        if (!is_numeric($before)) {
51✔
2406
            $objReferenceHelper = ReferenceHelper::getInstance();
50✔
2407
            $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
50✔
2408
        } else {
2409
            throw new Exception('Column references should not be numeric.');
1✔
2410
        }
2411

2412
        return $this;
50✔
2413
    }
2414

2415
    /**
2416
     * Insert a new column, updating all possible related data.
2417
     *
2418
     * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell)
2419
     * @param int $numberOfColumns Number of new columns to insert
2420
     *
2421
     * @return $this
2422
     */
2423
    public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1): static
2✔
2424
    {
2425
        if ($beforeColumnIndex >= 1) {
2✔
2426
            return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
1✔
2427
        }
2428

2429
        throw new Exception('Columns can only be inserted before at least column A (1).');
1✔
2430
    }
2431

2432
    /**
2433
     * Delete a row, updating all possible related data.
2434
     *
2435
     * @param int $row Remove rows, starting with this row number
2436
     * @param int $numberOfRows Number of rows to remove
2437
     *
2438
     * @return $this
2439
     */
2440
    public function removeRow(int $row, int $numberOfRows = 1): static
53✔
2441
    {
2442
        if ($row < 1) {
53✔
2443
            throw new Exception('Rows to be deleted should at least start from row 1.');
1✔
2444
        }
2445
        $startRow = $row;
52✔
2446
        $endRow = $startRow + $numberOfRows - 1;
52✔
2447
        $removeKeys = [];
52✔
2448
        $addKeys = [];
52✔
2449
        foreach ($this->mergeCells as $key => $value) {
52✔
2450
            if (
2451
                Preg::isMatch(
21✔
2452
                    '/^([a-z]{1,3})(\d+):([a-z]{1,3})(\d+)/i',
21✔
2453
                    $key,
21✔
2454
                    $matches
21✔
2455
                )
21✔
2456
            ) {
2457
                $startMergeInt = (int) $matches[2];
21✔
2458
                $endMergeInt = (int) $matches[4];
21✔
2459
                if ($startMergeInt >= $startRow) {
21✔
2460
                    if ($startMergeInt <= $endRow) {
21✔
2461
                        $removeKeys[] = $key;
3✔
2462
                    }
2463
                } elseif ($endMergeInt >= $startRow) {
1✔
2464
                    if ($endMergeInt <= $endRow) {
1✔
2465
                        $temp = $endMergeInt - 1;
1✔
2466
                        $removeKeys[] = $key;
1✔
2467
                        if ($temp !== $startMergeInt) {
1✔
2468
                            $temp3 = $matches[1] . $matches[2] . ':' . $matches[3] . $temp;
1✔
2469
                            $addKeys[] = $temp3;
1✔
2470
                        }
2471
                    }
2472
                }
2473
            }
2474
        }
2475
        foreach ($removeKeys as $key) {
52✔
2476
            unset($this->mergeCells[$key]);
3✔
2477
        }
2478
        foreach ($addKeys as $key) {
52✔
2479
            $this->mergeCells[$key] = $key;
1✔
2480
        }
2481

2482
        $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows);
52✔
2483
        $highestRow = $this->getHighestDataRow();
52✔
2484
        $removedRowsCounter = 0;
52✔
2485

2486
        for ($r = 0; $r < $numberOfRows; ++$r) {
52✔
2487
            if ($row + $r <= $highestRow) {
52✔
2488
                $this->cellCollection->removeRow($row + $r);
40✔
2489
                ++$removedRowsCounter;
40✔
2490
            }
2491
        }
2492

2493
        $objReferenceHelper = ReferenceHelper::getInstance();
52✔
2494
        $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
52✔
2495
        for ($r = 0; $r < $removedRowsCounter; ++$r) {
52✔
2496
            $this->cellCollection->removeRow($highestRow);
40✔
2497
            --$highestRow;
40✔
2498
        }
2499

2500
        $this->rowDimensions = $holdRowDimensions;
52✔
2501

2502
        return $this;
52✔
2503
    }
2504

2505
    /** @return RowDimension[] */
2506
    private function removeRowDimensions(int $row, int $numberOfRows): array
52✔
2507
    {
2508
        $highRow = $row + $numberOfRows - 1;
52✔
2509
        $holdRowDimensions = [];
52✔
2510
        foreach ($this->rowDimensions as $rowDimension) {
52✔
2511
            $num = $rowDimension->getRowIndex();
5✔
2512
            if ($num < $row) {
5✔
2513
                $holdRowDimensions[$num] = $rowDimension;
3✔
2514
            } elseif ($num > $highRow) {
5✔
2515
                $num -= $numberOfRows;
4✔
2516
                $cloneDimension = clone $rowDimension;
4✔
2517
                $cloneDimension->setRowIndex($num);
4✔
2518
                $holdRowDimensions[$num] = $cloneDimension;
4✔
2519
            }
2520
        }
2521

2522
        return $holdRowDimensions;
52✔
2523
    }
2524

2525
    /**
2526
     * Remove a column, updating all possible related data.
2527
     *
2528
     * @param string $column Remove columns starting with this column name, eg: 'A'
2529
     * @param int $numberOfColumns Number of columns to remove
2530
     *
2531
     * @return $this
2532
     */
2533
    public function removeColumn(string $column, int $numberOfColumns = 1): static
43✔
2534
    {
2535
        if (is_numeric($column)) {
43✔
2536
            throw new Exception('Column references should not be numeric.');
1✔
2537
        }
2538
        $startColumnInt = Coordinate::columnIndexFromString($column);
42✔
2539
        $endColumnInt = $startColumnInt + $numberOfColumns - 1;
42✔
2540
        $removeKeys = [];
42✔
2541
        $addKeys = [];
42✔
2542
        foreach ($this->mergeCells as $key => $value) {
42✔
2543
            if (
2544
                Preg::isMatch(
19✔
2545
                    '/^([a-z]{1,3})(\d+):([a-z]{1,3})(\d+)/i',
19✔
2546
                    $key,
19✔
2547
                    $matches
19✔
2548
                )
19✔
2549
            ) {
2550
                $startMergeInt = Coordinate::columnIndexFromString($matches[1]);
19✔
2551
                $endMergeInt = Coordinate::columnIndexFromString($matches[3]);
19✔
2552
                if ($startMergeInt >= $startColumnInt) {
19✔
2553
                    if ($startMergeInt <= $endColumnInt) {
2✔
2554
                        $removeKeys[] = $key;
2✔
2555
                    }
2556
                } elseif ($endMergeInt >= $startColumnInt) {
18✔
2557
                    if ($endMergeInt <= $endColumnInt) {
18✔
2558
                        $temp = Coordinate::columnIndexFromString($matches[3]) - 1;
1✔
2559
                        $temp2 = Coordinate::stringFromColumnIndex($temp);
1✔
2560
                        $removeKeys[] = $key;
1✔
2561
                        if ($temp2 !== $matches[1]) {
1✔
2562
                            $temp3 = $matches[1] . $matches[2] . ':' . $temp2 . $matches[4];
1✔
2563
                            $addKeys[] = $temp3;
1✔
2564
                        }
2565
                    }
2566
                }
2567
            }
2568
        }
2569
        foreach ($removeKeys as $key) {
42✔
2570
            unset($this->mergeCells[$key]);
2✔
2571
        }
2572
        foreach ($addKeys as $key) {
42✔
2573
            $this->mergeCells[$key] = $key;
1✔
2574
        }
2575

2576
        $highestColumn = $this->getHighestDataColumn();
42✔
2577
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
42✔
2578
        $pColumnIndex = Coordinate::columnIndexFromString($column);
42✔
2579

2580
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
42✔
2581

2582
        $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
42✔
2583
        $objReferenceHelper = ReferenceHelper::getInstance();
42✔
2584
        $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
42✔
2585

2586
        $this->columnDimensions = $holdColumnDimensions;
42✔
2587

2588
        if ($pColumnIndex > $highestColumnIndex) {
42✔
2589
            return $this;
9✔
2590
        }
2591

2592
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
33✔
2593

2594
        for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
33✔
2595
            $this->cellCollection->removeColumn($highestColumn);
33✔
2596
            $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
33✔
2597
        }
2598

2599
        $this->garbageCollect();
33✔
2600

2601
        return $this;
33✔
2602
    }
2603

2604
    /** @return ColumnDimension[] */
2605
    private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array
42✔
2606
    {
2607
        $highCol = $pColumnIndex + $numberOfColumns - 1;
42✔
2608
        $holdColumnDimensions = [];
42✔
2609
        foreach ($this->columnDimensions as $columnDimension) {
42✔
2610
            $num = $columnDimension->getColumnNumeric();
18✔
2611
            if ($num < $pColumnIndex) {
18✔
2612
                $str = $columnDimension->getColumnIndex();
18✔
2613
                $holdColumnDimensions[$str] = $columnDimension;
18✔
2614
            } elseif ($num > $highCol) {
18✔
2615
                $cloneDimension = clone $columnDimension;
18✔
2616
                $cloneDimension->setColumnNumeric($num - $numberOfColumns);
18✔
2617
                $str = $cloneDimension->getColumnIndex();
18✔
2618
                $holdColumnDimensions[$str] = $cloneDimension;
18✔
2619
            }
2620
        }
2621

2622
        return $holdColumnDimensions;
42✔
2623
    }
2624

2625
    /**
2626
     * Remove a column, updating all possible related data.
2627
     *
2628
     * @param int $columnIndex Remove starting with this column Index (numeric column coordinate)
2629
     * @param int $numColumns Number of columns to remove
2630
     *
2631
     * @return $this
2632
     */
2633
    public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static
3✔
2634
    {
2635
        if ($columnIndex >= 1) {
3✔
2636
            return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2✔
2637
        }
2638

2639
        throw new Exception('Columns to be deleted should at least start from column A (1)');
1✔
2640
    }
2641

2642
    /**
2643
     * Show gridlines?
2644
     */
2645
    public function getShowGridlines(): bool
1,145✔
2646
    {
2647
        return $this->showGridlines;
1,145✔
2648
    }
2649

2650
    /**
2651
     * Set show gridlines.
2652
     *
2653
     * @param bool $showGridLines Show gridlines (true/false)
2654
     *
2655
     * @return $this
2656
     */
2657
    public function setShowGridlines(bool $showGridLines): self
928✔
2658
    {
2659
        $this->showGridlines = $showGridLines;
928✔
2660

2661
        return $this;
928✔
2662
    }
2663

2664
    /**
2665
     * Print gridlines?
2666
     */
2667
    public function getPrintGridlines(): bool
1,168✔
2668
    {
2669
        return $this->printGridlines;
1,168✔
2670
    }
2671

2672
    /**
2673
     * Set print gridlines.
2674
     *
2675
     * @param bool $printGridLines Print gridlines (true/false)
2676
     *
2677
     * @return $this
2678
     */
2679
    public function setPrintGridlines(bool $printGridLines): self
606✔
2680
    {
2681
        $this->printGridlines = $printGridLines;
606✔
2682

2683
        return $this;
606✔
2684
    }
2685

2686
    /**
2687
     * Show row and column headers?
2688
     */
2689
    public function getShowRowColHeaders(): bool
589✔
2690
    {
2691
        return $this->showRowColHeaders;
589✔
2692
    }
2693

2694
    /**
2695
     * Set show row and column headers.
2696
     *
2697
     * @param bool $showRowColHeaders Show row and column headers (true/false)
2698
     *
2699
     * @return $this
2700
     */
2701
    public function setShowRowColHeaders(bool $showRowColHeaders): self
445✔
2702
    {
2703
        $this->showRowColHeaders = $showRowColHeaders;
445✔
2704

2705
        return $this;
445✔
2706
    }
2707

2708
    /**
2709
     * Show summary below? (Row/Column outlining).
2710
     */
2711
    public function getShowSummaryBelow(): bool
590✔
2712
    {
2713
        return $this->showSummaryBelow;
590✔
2714
    }
2715

2716
    /**
2717
     * Set show summary below.
2718
     *
2719
     * @param bool $showSummaryBelow Show summary below (true/false)
2720
     *
2721
     * @return $this
2722
     */
2723
    public function setShowSummaryBelow(bool $showSummaryBelow): self
444✔
2724
    {
2725
        $this->showSummaryBelow = $showSummaryBelow;
444✔
2726

2727
        return $this;
444✔
2728
    }
2729

2730
    /**
2731
     * Show summary right? (Row/Column outlining).
2732
     */
2733
    public function getShowSummaryRight(): bool
590✔
2734
    {
2735
        return $this->showSummaryRight;
590✔
2736
    }
2737

2738
    /**
2739
     * Set show summary right.
2740
     *
2741
     * @param bool $showSummaryRight Show summary right (true/false)
2742
     *
2743
     * @return $this
2744
     */
2745
    public function setShowSummaryRight(bool $showSummaryRight): self
444✔
2746
    {
2747
        $this->showSummaryRight = $showSummaryRight;
444✔
2748

2749
        return $this;
444✔
2750
    }
2751

2752
    /**
2753
     * Get comments.
2754
     *
2755
     * @return Comment[]
2756
     */
2757
    public function getComments(): array
1,221✔
2758
    {
2759
        return $this->comments;
1,221✔
2760
    }
2761

2762
    /**
2763
     * Set comments array for the entire sheet.
2764
     *
2765
     * @param Comment[] $comments
2766
     *
2767
     * @return $this
2768
     */
2769
    public function setComments(array $comments): self
127✔
2770
    {
2771
        $this->comments = $comments;
127✔
2772

2773
        return $this;
127✔
2774
    }
2775

2776
    /**
2777
     * Remove comment from cell.
2778
     *
2779
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2780
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2781
     *
2782
     * @return $this
2783
     */
2784
    public function removeComment(CellAddress|string|array $cellCoordinate): self
58✔
2785
    {
2786
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
58✔
2787

2788
        if (Coordinate::coordinateIsRange($cellAddress)) {
58✔
2789
            throw new Exception('Cell coordinate string can not be a range of cells.');
1✔
2790
        } elseif (str_contains($cellAddress, '$')) {
57✔
2791
            throw new Exception('Cell coordinate string must not be absolute.');
1✔
2792
        } elseif ($cellAddress == '') {
56✔
2793
            throw new Exception('Cell coordinate can not be zero-length string.');
1✔
2794
        }
2795
        // Check if we have a comment for this cell and delete it
2796
        if (isset($this->comments[$cellAddress])) {
55✔
2797
            unset($this->comments[$cellAddress]);
3✔
2798
        }
2799

2800
        return $this;
55✔
2801
    }
2802

2803
    /**
2804
     * Get comment for cell.
2805
     *
2806
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2807
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2808
     */
2809
    public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment
120✔
2810
    {
2811
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
120✔
2812

2813
        if (Coordinate::coordinateIsRange($cellAddress)) {
120✔
2814
            throw new Exception('Cell coordinate string can not be a range of cells.');
1✔
2815
        } elseif (str_contains($cellAddress, '$')) {
119✔
2816
            throw new Exception('Cell coordinate string must not be absolute.');
1✔
2817
        } elseif ($cellAddress == '') {
118✔
2818
            throw new Exception('Cell coordinate can not be zero-length string.');
1✔
2819
        }
2820

2821
        // Check if we already have a comment for this cell.
2822
        if (isset($this->comments[$cellAddress])) {
117✔
2823
            return $this->comments[$cellAddress];
83✔
2824
        }
2825

2826
        // If not, create a new comment.
2827
        $newComment = new Comment();
117✔
2828
        if ($attachNew) {
117✔
2829
            $this->comments[$cellAddress] = $newComment;
117✔
2830
        }
2831

2832
        return $newComment;
117✔
2833
    }
2834

2835
    /**
2836
     * Get active cell.
2837
     *
2838
     * @return string Example: 'A1'
2839
     */
2840
    public function getActiveCell(): string
10,950✔
2841
    {
2842
        return $this->activeCell;
10,950✔
2843
    }
2844

2845
    /**
2846
     * Get selected cells.
2847
     */
2848
    public function getSelectedCells(): string
11,004✔
2849
    {
2850
        return $this->selectedCells;
11,004✔
2851
    }
2852

2853
    /**
2854
     * Selected cell.
2855
     *
2856
     * @param string $coordinate Cell (i.e. A1)
2857
     *
2858
     * @return $this
2859
     */
2860
    public function setSelectedCell(string $coordinate): static
38✔
2861
    {
2862
        return $this->setSelectedCells($coordinate);
38✔
2863
    }
2864

2865
    /**
2866
     * Select a range of cells.
2867
     *
2868
     * @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'
2869
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2870
     *              or a CellAddress or AddressRange object.
2871
     *
2872
     * @return $this
2873
     */
2874
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
10,953✔
2875
    {
2876
        if (is_string($coordinate)) {
10,953✔
2877
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
10,953✔
2878
        }
2879
        $coordinate = Validations::validateCellOrCellRange($coordinate);
10,953✔
2880

2881
        if (Coordinate::coordinateIsRange($coordinate)) {
10,953✔
2882
            [$first] = Coordinate::splitRange($coordinate);
540✔
2883
            $this->activeCell = $first[0];
540✔
2884
        } else {
2885
            $this->activeCell = $coordinate;
10,922✔
2886
        }
2887
        $this->selectedCells = $coordinate;
10,953✔
2888
        $this->setSelectedCellsActivePane();
10,953✔
2889

2890
        return $this;
10,953✔
2891
    }
2892

2893
    private function setSelectedCellsActivePane(): void
10,954✔
2894
    {
2895
        if (!empty($this->freezePane)) {
10,954✔
2896
            $coordinateC = Coordinate::indexesFromString($this->freezePane);
48✔
2897
            $coordinateT = Coordinate::indexesFromString($this->activeCell);
48✔
2898
            if ($coordinateC[0] === 1) {
48✔
2899
                $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft';
26✔
2900
            } elseif ($coordinateC[1] === 1) {
24✔
2901
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
3✔
2902
            } elseif ($coordinateT[1] <= $coordinateC[1]) {
22✔
2903
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
22✔
2904
            } else {
2905
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight';
10✔
2906
            }
2907
            $this->setActivePane($activePane);
48✔
2908
            $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell);
48✔
2909
        }
2910
    }
2911

2912
    /**
2913
     * Get right-to-left.
2914
     */
2915
    public function getRightToLeft(): bool
1,171✔
2916
    {
2917
        return $this->rightToLeft;
1,171✔
2918
    }
2919

2920
    /**
2921
     * Set right-to-left.
2922
     *
2923
     * @param bool $value Right-to-left true/false
2924
     *
2925
     * @return $this
2926
     */
2927
    public function setRightToLeft(bool $value): static
168✔
2928
    {
2929
        $this->rightToLeft = $value;
168✔
2930

2931
        return $this;
168✔
2932
    }
2933

2934
    /**
2935
     * Fill worksheet from values in array.
2936
     *
2937
     * @param mixed[]|mixed[][] $source Source array
2938
     * @param mixed $nullValue Value in source array that stands for blank cell
2939
     * @param string $startCell Insert array starting from this cell address as the top left coordinate
2940
     * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2941
     *
2942
     * @return $this
2943
     */
2944
    public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static
907✔
2945
    {
2946
        //    Convert a 1-D array to 2-D (for ease of looping)
2947
        if (!is_array(end($source))) {
907✔
2948
            $source = [$source];
49✔
2949
        }
2950
        /** @var mixed[][] $source */
2951

2952
        // start coordinate
2953
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
907✔
2954
        $startRow = (int) $startRow;
907✔
2955

2956
        // Loop through $source
2957
        if ($strictNullComparison) {
907✔
2958
            foreach ($source as $rowData) {
410✔
2959
                /** @var string */
2960
                $currentColumn = $startColumn;
410✔
2961
                foreach ($rowData as $cellValue) {
410✔
2962
                    if ($cellValue !== $nullValue) {
410✔
2963
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
410✔
2964
                    }
2965
                    StringHelper::stringIncrement($currentColumn);
410✔
2966
                }
2967
                ++$startRow;
410✔
2968
            }
2969
        } else {
2970
            foreach ($source as $rowData) {
506✔
2971
                $currentColumn = $startColumn;
506✔
2972
                foreach ($rowData as $cellValue) {
506✔
2973
                    if ($cellValue != $nullValue) {
505✔
2974
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
499✔
2975
                    }
2976
                    StringHelper::stringIncrement($currentColumn);
505✔
2977
                }
2978
                ++$startRow;
506✔
2979
            }
2980
        }
2981

2982
        return $this;
907✔
2983
    }
2984

2985
    /**
2986
     * @param bool $calculateFormulas Whether to calculate cell's value if it is a formula.
2987
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2988
     * @param bool $formatData Whether to format data according to cell's style.
2989
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
2990
     * @param bool $oldCalculatedValue If calculateFormulas is false and this is true, use oldCalculatedFormula instead.
2991
     *
2992
     * @throws Exception
2993
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2994
     */
2995
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue, bool $lessFloatPrecision = false, $oldCalculatedValue = false): mixed
201✔
2996
    {
2997
        $returnValue = $nullValue;
201✔
2998

2999
        if ($cell->getValue() !== null) {
201✔
3000
            if ($cell->getValue() instanceof RichText) {
201✔
3001
                $returnValue = $cell->getValue()->getPlainText();
4✔
3002
            } elseif ($calculateFormulas) {
201✔
3003
                $returnValue = $cell->getCalculatedValue();
172✔
3004
            } elseif ($oldCalculatedValue && ($cell->getDataType() === DataType::TYPE_FORMULA)) {
35✔
3005
                $returnValue = $cell->getOldCalculatedValue() ?? $cell->getValue();
2✔
3006
            } else {
3007
                $returnValue = $cell->getValue();
35✔
3008
            }
3009

3010
            if ($formatData) {
201✔
3011
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
128✔
3012
                /** @var null|bool|float|int|RichText|string */
3013
                $returnValuex = $returnValue;
128✔
3014
                $returnValue = NumberFormat::toFormattedString(
128✔
3015
                    $returnValuex,
128✔
3016
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL,
128✔
3017
                    lessFloatPrecision: $lessFloatPrecision
128✔
3018
                );
128✔
3019
            }
3020
        }
3021

3022
        return $returnValue;
201✔
3023
    }
3024

3025
    /**
3026
     * Create array from a range of cells.
3027
     *
3028
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3029
     * @param bool $calculateFormulas Should formulas be calculated?
3030
     * @param bool $formatData Should formatting be applied to cell values?
3031
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3032
     *                             True - Return rows and columns indexed by their actual row and column IDs
3033
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3034
     *                            True - Don't return values for rows/columns that are defined as hidden.
3035
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3036
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3037
     * @param bool $oldCalculatedValue If calculateFormulas is false and this is true, use oldCalculatedFormula instead.
3038
     *
3039
     * @return mixed[][]
3040
     */
3041
    public function rangeToArray(
166✔
3042
        string $range,
3043
        mixed $nullValue = null,
3044
        bool $calculateFormulas = true,
3045
        bool $formatData = true,
3046
        bool $returnCellRef = false,
3047
        bool $ignoreHidden = false,
3048
        bool $reduceArrays = false,
3049
        bool $lessFloatPrecision = false,
3050
        bool $oldCalculatedValue = false,
3051
    ): array {
3052
        $returnValue = [];
166✔
3053

3054
        // Loop through rows
3055
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision, $oldCalculatedValue) as $rowRef => $rowArray) {
166✔
3056
            /** @var int $rowRef */
3057
            $returnValue[$rowRef] = $rowArray;
166✔
3058
        }
3059

3060
        // Return
3061
        return $returnValue;
166✔
3062
    }
3063

3064
    /**
3065
     * Create array from a multiple ranges of cells. (such as A1:A3,A15,B17:C17).
3066
     *
3067
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3068
     * @param bool $calculateFormulas Should formulas be calculated?
3069
     * @param bool $formatData Should formatting be applied to cell values?
3070
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3071
     *                             True - Return rows and columns indexed by their actual row and column IDs
3072
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3073
     *                            True - Don't return values for rows/columns that are defined as hidden.
3074
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3075
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3076
     * @param bool $oldCalculatedValue If calculateFormulas is false and this is true, use oldCalculatedFormula instead.
3077
     *
3078
     * @return mixed[][]
3079
     */
3080
    public function rangesToArray(
6✔
3081
        string $ranges,
3082
        mixed $nullValue = null,
3083
        bool $calculateFormulas = true,
3084
        bool $formatData = true,
3085
        bool $returnCellRef = false,
3086
        bool $ignoreHidden = false,
3087
        bool $reduceArrays = false,
3088
        bool $lessFloatPrecision = false,
3089
        bool $oldCalculatedValue = false,
3090
    ): array {
3091
        $returnValue = [];
6✔
3092

3093
        $parts = explode(',', $ranges);
6✔
3094
        foreach ($parts as $part) {
6✔
3095
            // Loop through rows
3096
            foreach ($this->rangeToArrayYieldRows($part, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision, $oldCalculatedValue) as $rowRef => $rowArray) {
6✔
3097
                /** @var int $rowRef */
3098
                $returnValue[$rowRef] = $rowArray;
6✔
3099
            }
3100
        }
3101

3102
        // Return
3103
        return $returnValue;
6✔
3104
    }
3105

3106
    /**
3107
     * Create array from a range of cells, yielding each row in turn.
3108
     *
3109
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3110
     * @param bool $calculateFormulas Should formulas be calculated?
3111
     * @param bool $formatData Should formatting be applied to cell values?
3112
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3113
     *                             True - Return rows and columns indexed by their actual row and column IDs
3114
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3115
     *                            True - Don't return values for rows/columns that are defined as hidden.
3116
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3117
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3118
     * @param bool $oldCalculatedValue If calculateFormulas is false and this is true, use oldCalculatedFormula instead.
3119
     *
3120
     * @return Generator<array<mixed>>
3121
     */
3122
    public function rangeToArrayYieldRows(
201✔
3123
        string $range,
3124
        mixed $nullValue = null,
3125
        bool $calculateFormulas = true,
3126
        bool $formatData = true,
3127
        bool $returnCellRef = false,
3128
        bool $ignoreHidden = false,
3129
        bool $reduceArrays = false,
3130
        bool $lessFloatPrecision = false,
3131
        bool $oldCalculatedValue = false,
3132
    ) {
3133
        $range = Validations::validateCellOrCellRange($range);
201✔
3134

3135
        //    Identify the range that we need to extract from the worksheet
3136
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
201✔
3137
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
201✔
3138
        $minRow = $rangeStart[1];
201✔
3139
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
201✔
3140
        $maxRow = $rangeEnd[1];
201✔
3141
        $minColInt = $rangeStart[0];
201✔
3142
        $maxColInt = $rangeEnd[0];
201✔
3143

3144
        StringHelper::stringIncrement($maxCol);
201✔
3145
        /** @var array<string, bool> */
3146
        $hiddenColumns = [];
201✔
3147
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
201✔
3148
        $hideColumns = !empty($hiddenColumns);
201✔
3149

3150
        $keys = $this->cellCollection->getSortedCoordinatesInt();
201✔
3151
        $keyIndex = 0;
201✔
3152
        $keysCount = count($keys);
201✔
3153
        // Loop through rows
3154
        for ($row = $minRow; $row <= $maxRow; ++$row) {
201✔
3155
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
201✔
3156
                continue;
4✔
3157
            }
3158
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
201✔
3159
            $returnValue = $nullRow;
201✔
3160

3161
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
201✔
3162
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
201✔
3163

3164
            // Binary search to quickly approach the correct index
3165
            $keyIndex = intdiv($keysCount, 2);
201✔
3166
            $boundLow = 0;
201✔
3167
            $boundHigh = $keysCount - 1;
201✔
3168
            while ($boundLow <= $boundHigh) {
201✔
3169
                $keyIndex = intdiv($boundLow + $boundHigh, 2);
201✔
3170
                if ($keys[$keyIndex] < $index) {
201✔
3171
                    $boundLow = $keyIndex + 1;
167✔
3172
                } elseif ($keys[$keyIndex] > $index) {
201✔
3173
                    $boundHigh = $keyIndex - 1;
183✔
3174
                } else {
3175
                    break;
193✔
3176
                }
3177
            }
3178

3179
            // Realign to the proper index value
3180
            while ($keyIndex > 0 && $keys[$keyIndex] > $index) {
201✔
3181
                --$keyIndex;
14✔
3182
            }
3183
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
201✔
3184
                ++$keyIndex;
21✔
3185
            }
3186

3187
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
201✔
3188
                $key = $keys[$keyIndex];
201✔
3189
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
201✔
3190
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
201✔
3191
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
201✔
3192
                    $col = Coordinate::stringFromColumnIndex($thisCol);
201✔
3193
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
201✔
3194
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
201✔
3195
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
201✔
3196
                        if ($cell !== null) {
201✔
3197
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue, lessFloatPrecision: $lessFloatPrecision, oldCalculatedValue: $oldCalculatedValue);
201✔
3198
                            if ($reduceArrays) {
201✔
3199
                                while (is_array($value)) {
21✔
3200
                                    $value = array_shift($value);
19✔
3201
                                }
3202
                            }
3203
                            if ($value !== $nullValue) {
201✔
3204
                                $returnValue[$columnRef] = $value;
201✔
3205
                            }
3206
                        }
3207
                    }
3208
                }
3209
                ++$keyIndex;
201✔
3210
            }
3211

3212
            yield $rowRef => $returnValue;
201✔
3213
        }
3214
    }
3215

3216
    /**
3217
     * Prepare a row data filled with null values to deduplicate the memory areas for empty rows.
3218
     *
3219
     * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
3220
     * @param string $minCol Start column of the range
3221
     * @param string $maxCol End column of the range
3222
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3223
     *                              True - Return rows and columns indexed by their actual row and column IDs
3224
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3225
     *                             True - Don't return values for rows/columns that are defined as hidden.
3226
     * @param array<string, bool> $hiddenColumns
3227
     *
3228
     * @return mixed[]
3229
     */
3230
    private function buildNullRow(
201✔
3231
        mixed $nullValue,
3232
        string $minCol,
3233
        string $maxCol,
3234
        bool $returnCellRef,
3235
        bool $ignoreHidden,
3236
        array &$hiddenColumns
3237
    ): array {
3238
        $nullRow = [];
201✔
3239
        $c = -1;
201✔
3240
        for ($col = $minCol; $col !== $maxCol; StringHelper::stringIncrement($col)) {
201✔
3241
            if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) {
201✔
3242
                $hiddenColumns[$col] = true;
2✔
3243
            } else {
3244
                $columnRef = $returnCellRef ? $col : ++$c;
201✔
3245
                $nullRow[$columnRef] = $nullValue;
201✔
3246
            }
3247
        }
3248

3249
        return $nullRow;
201✔
3250
    }
3251

3252
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
19✔
3253
    {
3254
        $namedRange = DefinedName::resolveName($definedName, $this);
19✔
3255
        if ($namedRange === null) {
19✔
3256
            if ($returnNullIfInvalid) {
6✔
3257
                return null;
5✔
3258
            }
3259

3260
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
1✔
3261
        }
3262

3263
        if ($namedRange->isFormula()) {
13✔
UNCOV
3264
            if ($returnNullIfInvalid) {
×
UNCOV
3265
                return null;
×
3266
            }
3267

UNCOV
3268
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
×
3269
        }
3270

3271
        if ($namedRange->getLocalOnly()) {
13✔
3272
            $worksheet = $namedRange->getWorksheet();
2✔
3273
            if ($worksheet === null || $this !== $worksheet) {
2✔
UNCOV
3274
                if ($returnNullIfInvalid) {
×
UNCOV
3275
                    return null;
×
3276
                }
3277

3278
                throw new Exception(
×
UNCOV
3279
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
×
UNCOV
3280
                );
×
3281
            }
3282
        }
3283

3284
        return $namedRange;
13✔
3285
    }
3286

3287
    /**
3288
     * Create array from a range of cells.
3289
     *
3290
     * @param string $definedName The Named Range that should be returned
3291
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3292
     * @param bool $calculateFormulas Should formulas be calculated?
3293
     * @param bool $formatData Should formatting be applied to cell values?
3294
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3295
     *                             True - Return rows and columns indexed by their actual row and column IDs
3296
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3297
     *                            True - Don't return values for rows/columns that are defined as hidden.
3298
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3299
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3300
     * @param bool $oldCalculatedValue If calculateFormulas is false and this is true, use oldCalculatedFormula instead.
3301
     *
3302
     * @return mixed[][]
3303
     */
3304
    public function namedRangeToArray(
2✔
3305
        string $definedName,
3306
        mixed $nullValue = null,
3307
        bool $calculateFormulas = true,
3308
        bool $formatData = true,
3309
        bool $returnCellRef = false,
3310
        bool $ignoreHidden = false,
3311
        bool $reduceArrays = false,
3312
        bool $lessFloatPrecision = false,
3313
        bool $oldCalculatedValue = false,
3314
    ): array {
3315
        $retVal = [];
2✔
3316
        $namedRange = $this->validateNamedRange($definedName);
2✔
3317
        if ($namedRange !== null) {
1✔
3318
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
1✔
3319
            $cellRange = str_replace('$', '', $cellRange);
1✔
3320
            $workSheet = $namedRange->getWorksheet();
1✔
3321
            if ($workSheet !== null) {
1✔
3322
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision, $oldCalculatedValue);
1✔
3323
            }
3324
        }
3325

3326
        return $retVal;
1✔
3327
    }
3328

3329
    /**
3330
     * Create array from worksheet.
3331
     *
3332
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3333
     * @param bool $calculateFormulas Should formulas be calculated?
3334
     * @param bool $formatData Should formatting be applied to cell values?
3335
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3336
     *                             True - Return rows and columns indexed by their actual row and column IDs
3337
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3338
     *                            True - Don't return values for rows/columns that are defined as hidden.
3339
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3340
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3341
     * @param bool $oldCalculatedValue If calculateFormulas is false and this is true, use oldCalculatedFormula instead.
3342
     *
3343
     * @return mixed[][]
3344
     */
3345
    public function toArray(
97✔
3346
        mixed $nullValue = null,
3347
        bool $calculateFormulas = true,
3348
        bool $formatData = true,
3349
        bool $returnCellRef = false,
3350
        bool $ignoreHidden = false,
3351
        bool $reduceArrays = false,
3352
        bool $lessFloatPrecision = false,
3353
        bool $oldCalculatedValue = false,
3354
    ): array {
3355
        // Garbage collect...
3356
        $this->garbageCollect();
97✔
3357
        $this->calculateArrays($calculateFormulas);
97✔
3358

3359
        //    Identify the range that we need to extract from the worksheet
3360
        $maxCol = $this->getHighestColumn();
97✔
3361
        $maxRow = $this->getHighestRow();
97✔
3362

3363
        // Return
3364
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision, $oldCalculatedValue);
97✔
3365
    }
3366

3367
    /**
3368
     * Get row iterator.
3369
     *
3370
     * @param int $startRow The row number at which to start iterating
3371
     * @param ?int $endRow The row number at which to stop iterating
3372
     */
3373
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
117✔
3374
    {
3375
        return new RowIterator($this, $startRow, $endRow);
117✔
3376
    }
3377

3378
    /**
3379
     * Get column iterator.
3380
     *
3381
     * @param string $startColumn The column address at which to start iterating
3382
     * @param ?string $endColumn The column address at which to stop iterating
3383
     */
3384
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
39✔
3385
    {
3386
        return new ColumnIterator($this, $startColumn, $endColumn);
39✔
3387
    }
3388

3389
    /**
3390
     * Run PhpSpreadsheet garbage collector.
3391
     *
3392
     * @return $this
3393
     */
3394
    public function garbageCollect(): static
1,317✔
3395
    {
3396
        // Flush cache
3397
        $this->cellCollection->get('A1');
1,317✔
3398

3399
        // Lookup highest column and highest row if cells are cleaned
3400
        $colRow = $this->cellCollection->getHighestRowAndColumn();
1,317✔
3401
        $highestRow = $colRow['row'];
1,317✔
3402
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
1,317✔
3403

3404
        // Loop through column dimensions
3405
        foreach ($this->columnDimensions as $dimension) {
1,317✔
3406
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
195✔
3407
        }
3408

3409
        // Loop through row dimensions
3410
        foreach ($this->rowDimensions as $dimension) {
1,317✔
3411
            $highestRow = max($highestRow, $dimension->getRowIndex());
124✔
3412
        }
3413

3414
        // Cache values
3415
        $this->cachedHighestColumn = max(1, $highestColumn);
1,317✔
3416
        /** @var int $highestRow */
3417
        $this->cachedHighestRow = $highestRow;
1,317✔
3418

3419
        // Return
3420
        return $this;
1,317✔
3421
    }
3422

3423
    /**
3424
     * @deprecated 5.2.0 Serves no useful purpose. No replacement.
3425
     *
3426
     * @codeCoverageIgnore
3427
     */
3428
    public function getHashInt(): int
3429
    {
3430
        return spl_object_id($this);
3431
    }
3432

3433
    /**
3434
     * Extract worksheet title from range.
3435
     *
3436
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3437
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3438
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3439
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3440
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3441
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3442
     *
3443
     * @param ?string $range Range to extract title from
3444
     * @param bool $returnRange Return range? (see example)
3445
     *
3446
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3447
     */
3448
    public static function extractSheetTitle(?string $range, bool $returnRange = false, bool $unapostrophize = false): array|null|string
11,184✔
3449
    {
3450
        if (empty($range)) {
11,184✔
3451
            return $returnRange ? [null, null] : null;
13✔
3452
        }
3453

3454
        // Sheet title included?
3455
        if (($sep = strrpos($range, '!')) === false) {
11,182✔
3456
            return $returnRange ? ['', $range] : '';
11,153✔
3457
        }
3458

3459
        if ($returnRange) {
1,494✔
3460
            $title = substr($range, 0, $sep);
1,494✔
3461
            if ($unapostrophize) {
1,494✔
3462
                $title = self::unApostrophizeTitle($title);
1,434✔
3463
            }
3464

3465
            return [$title, substr($range, $sep + 1)];
1,494✔
3466
        }
3467

3468
        return substr($range, $sep + 1);
7✔
3469
    }
3470

3471
    public static function unApostrophizeTitle(?string $title): string
1,448✔
3472
    {
3473
        $title ??= '';
1,448✔
3474
        if (str_starts_with($title, "'") && str_ends_with($title, "'")) {
1,448✔
3475
            $title = str_replace("''", "'", substr($title, 1, -1));
1,372✔
3476
        }
3477

3478
        return $title;
1,448✔
3479
    }
3480

3481
    /**
3482
     * Get hyperlink.
3483
     *
3484
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3485
     */
3486
    public function getHyperlink(string $cellCoordinate): Hyperlink
113✔
3487
    {
3488
        $this->getCell($cellCoordinate)->setHadHyperlink(true);
113✔
3489
        // return hyperlink if we already have one
3490
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
113✔
3491
            return $this->hyperlinkCollection[$cellCoordinate];
61✔
3492
        }
3493

3494
        // else create hyperlink
3495
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
113✔
3496

3497
        return $this->hyperlinkCollection[$cellCoordinate];
113✔
3498
    }
3499

3500
    /**
3501
     * Set hyperlink.
3502
     *
3503
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3504
     *
3505
     * @return $this
3506
     */
3507
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null, bool $reset = true): static
588✔
3508
    {
3509
        if ($hyperlink === null) {
588✔
3510
            unset($this->hyperlinkCollection[$cellCoordinate]);
587✔
3511
            if ($reset) {
587✔
3512
                $this->getCell($cellCoordinate)
553✔
3513
                    ->setHadHyperlink(false);
553✔
3514
            }
3515
        } else {
3516
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
36✔
3517
            $this->getCell($cellCoordinate)->setHadHyperlink(true);
36✔
3518
        }
3519

3520
        return $this;
588✔
3521
    }
3522

3523
    /**
3524
     * Hyperlink at a specific coordinate exists?
3525
     *
3526
     * @param string $coordinate eg: 'A1'
3527
     */
3528
    public function hyperlinkExists(string $coordinate): bool
675✔
3529
    {
3530
        return isset($this->hyperlinkCollection[$coordinate]);
675✔
3531
    }
3532

3533
    /**
3534
     * Get collection of hyperlinks.
3535
     *
3536
     * @return Hyperlink[]
3537
     */
3538
    public function getHyperlinkCollection(): array
698✔
3539
    {
3540
        return $this->hyperlinkCollection;
698✔
3541
    }
3542

3543
    /**
3544
     * Get data validation.
3545
     *
3546
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3547
     */
3548
    public function getDataValidation(string $cellCoordinate): DataValidation
37✔
3549
    {
3550
        // return data validation if we already have one
3551
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
37✔
3552
            return $this->dataValidationCollection[$cellCoordinate];
28✔
3553
        }
3554

3555
        // or if cell is part of a data validation range
3556
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
28✔
3557
            $keyParts = explode(' ', $key);
12✔
3558
            foreach ($keyParts as $keyPart) {
12✔
3559
                if ($keyPart === $cellCoordinate) {
12✔
3560
                    return $dataValidation;
1✔
3561
                }
3562
                if (str_contains($keyPart, ':')) {
12✔
3563
                    if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) {
9✔
3564
                        return $dataValidation;
9✔
3565
                    }
3566
                }
3567
            }
3568
        }
3569

3570
        // else create data validation
3571
        $dataValidation = new DataValidation();
20✔
3572
        $dataValidation->setSqref($cellCoordinate);
20✔
3573
        $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
20✔
3574

3575
        return $dataValidation;
20✔
3576
    }
3577

3578
    /**
3579
     * Set data validation.
3580
     *
3581
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3582
     *
3583
     * @return $this
3584
     */
3585
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
92✔
3586
    {
3587
        if ($dataValidation === null) {
92✔
3588
            unset($this->dataValidationCollection[$cellCoordinate]);
59✔
3589
        } else {
3590
            $dataValidation->setSqref($cellCoordinate);
40✔
3591
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
40✔
3592
        }
3593

3594
        return $this;
92✔
3595
    }
3596

3597
    /**
3598
     * Data validation at a specific coordinate exists?
3599
     *
3600
     * @param string $coordinate eg: 'A1'
3601
     */
3602
    public function dataValidationExists(string $coordinate): bool
25✔
3603
    {
3604
        if (isset($this->dataValidationCollection[$coordinate])) {
25✔
3605
            return true;
23✔
3606
        }
3607
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
8✔
3608
            $keyParts = explode(' ', $key);
7✔
3609
            foreach ($keyParts as $keyPart) {
7✔
3610
                if ($keyPart === $coordinate) {
7✔
3611
                    return true;
1✔
3612
                }
3613
                if (str_contains($keyPart, ':')) {
7✔
3614
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
2✔
3615
                        return true;
2✔
3616
                    }
3617
                }
3618
            }
3619
        }
3620

3621
        return false;
6✔
3622
    }
3623

3624
    /**
3625
     * Get collection of data validations.
3626
     *
3627
     * @return DataValidation[]
3628
     */
3629
    public function getDataValidationCollection(): array
699✔
3630
    {
3631
        $collectionCells = [];
699✔
3632
        $collectionRanges = [];
699✔
3633
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
699✔
3634
            if (Preg::isMatch('/[: ]/', $key)) {
27✔
3635
                $collectionRanges[$key] = $dataValidation;
15✔
3636
            } else {
3637
                $collectionCells[$key] = $dataValidation;
22✔
3638
            }
3639
        }
3640

3641
        return array_merge($collectionCells, $collectionRanges);
699✔
3642
    }
3643

3644
    /**
3645
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3646
     *
3647
     * @return string Adjusted range value
3648
     */
3649
    public function shrinkRangeToFit(string $range): string
×
3650
    {
3651
        $maxCol = $this->getHighestColumn();
×
UNCOV
3652
        $maxRow = $this->getHighestRow();
×
3653
        $maxCol = Coordinate::columnIndexFromString($maxCol);
×
3654

3655
        $rangeBlocks = explode(' ', $range);
×
UNCOV
3656
        foreach ($rangeBlocks as &$rangeSet) {
×
3657
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
×
3658

UNCOV
3659
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
×
3660
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3661
            }
UNCOV
3662
            if ($rangeBoundaries[0][1] > $maxRow) {
×
3663
                $rangeBoundaries[0][1] = $maxRow;
×
3664
            }
UNCOV
3665
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
×
3666
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3667
            }
UNCOV
3668
            if ($rangeBoundaries[1][1] > $maxRow) {
×
3669
                $rangeBoundaries[1][1] = $maxRow;
×
3670
            }
3671
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
×
3672
        }
3673
        unset($rangeSet);
×
3674

UNCOV
3675
        return implode(' ', $rangeBlocks);
×
3676
    }
3677

3678
    /**
3679
     * Get tab color.
3680
     */
3681
    public function getTabColor(): Color
23✔
3682
    {
3683
        if ($this->tabColor === null) {
23✔
3684
            $this->tabColor = new Color();
23✔
3685
        }
3686

3687
        return $this->tabColor;
23✔
3688
    }
3689

3690
    /**
3691
     * Reset tab color.
3692
     *
3693
     * @return $this
3694
     */
3695
    public function resetTabColor(): static
1✔
3696
    {
3697
        $this->tabColor = null;
1✔
3698

3699
        return $this;
1✔
3700
    }
3701

3702
    /**
3703
     * Tab color set?
3704
     */
3705
    public function isTabColorSet(): bool
591✔
3706
    {
3707
        return $this->tabColor !== null;
591✔
3708
    }
3709

3710
    /**
3711
     * Copy worksheet (!= clone!).
3712
     */
3713
    public function copy(): static
×
3714
    {
UNCOV
3715
        return clone $this;
×
3716
    }
3717

3718
    /**
3719
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3720
     *          exist in the collection for this row. false will be returned otherwise.
3721
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3722
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3723
     *                  cells, then the row will be considered empty.
3724
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3725
     *                  string value cells, then the row will be considered empty.
3726
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3727
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3728
     *                  will be considered empty.
3729
     *
3730
     * @param int $definitionOfEmptyFlags
3731
     *              Possible Flag Values are:
3732
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3733
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3734
     */
3735
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
9✔
3736
    {
3737
        try {
3738
            $iterator = new RowIterator($this, $rowId, $rowId);
9✔
3739
            $iterator->seek($rowId);
8✔
3740
            $row = $iterator->current();
8✔
3741
        } catch (Exception) {
1✔
3742
            return true;
1✔
3743
        }
3744

3745
        return $row->isEmpty($definitionOfEmptyFlags);
8✔
3746
    }
3747

3748
    /**
3749
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3750
     *          exist in the collection for this column. false will be returned otherwise.
3751
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3752
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3753
     *                  cells, then the column will be considered empty.
3754
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3755
     *                  string value cells, then the column will be considered empty.
3756
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3757
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3758
     *                  will be considered empty.
3759
     *
3760
     * @param int $definitionOfEmptyFlags
3761
     *              Possible Flag Values are:
3762
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3763
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3764
     */
3765
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
9✔
3766
    {
3767
        try {
3768
            $iterator = new ColumnIterator($this, $columnId, $columnId);
9✔
3769
            $iterator->seek($columnId);
8✔
3770
            $column = $iterator->current();
8✔
3771
        } catch (Exception) {
1✔
3772
            return true;
1✔
3773
        }
3774

3775
        return $column->isEmpty($definitionOfEmptyFlags);
8✔
3776
    }
3777

3778
    /**
3779
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3780
     */
3781
    public function __clone()
27✔
3782
    {
3783
        foreach (get_object_vars($this) as $key => $val) {
27✔
3784
            if ($key == 'parent') {
27✔
3785
                continue;
27✔
3786
            }
3787

3788
            if (is_object($val) || (is_array($val))) {
27✔
3789
                if ($key === 'cellCollection') {
27✔
3790
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
27✔
3791
                    $this->cellCollection = $newCollection;
27✔
3792
                } elseif ($key === 'drawingCollection') {
27✔
3793
                    $currentCollection = $this->drawingCollection;
27✔
3794
                    $this->drawingCollection = new ArrayObject();
27✔
3795
                    foreach ($currentCollection as $item) {
27✔
3796
                        $newDrawing = clone $item;
4✔
3797
                        $newDrawing->setWorksheet($this);
4✔
3798
                    }
3799
                } elseif ($key === 'inCellDrawingCollection') {
27✔
3800
                    $currentCollection = $this->inCellDrawingCollection;
27✔
3801
                    $this->inCellDrawingCollection = new ArrayObject();
27✔
3802
                    foreach ($currentCollection as $item) {
27✔
3803
                        $newDrawing = clone $item;
1✔
3804
                        $newDrawing->setWorksheet($this);
1✔
3805
                    }
3806
                } elseif ($key === 'tableCollection') {
27✔
3807
                    $currentCollection = $this->tableCollection;
27✔
3808
                    $this->tableCollection = new ArrayObject();
27✔
3809
                    foreach ($currentCollection as $item) {
27✔
3810
                        $newTable = clone $item;
1✔
3811
                        $newTable->setName($item->getName() . 'clone');
1✔
3812
                        $this->addTable($newTable);
1✔
3813
                    }
3814
                } elseif ($key === 'chartCollection') {
27✔
3815
                    $currentCollection = $this->chartCollection;
27✔
3816
                    $this->chartCollection = new ArrayObject();
27✔
3817
                    foreach ($currentCollection as $item) {
27✔
3818
                        $newChart = clone $item;
5✔
3819
                        $this->addChart($newChart);
5✔
3820
                    }
3821
                } elseif ($key === 'autoFilter') {
27✔
3822
                    $newAutoFilter = clone $this->autoFilter;
27✔
3823
                    $this->autoFilter = $newAutoFilter;
27✔
3824
                    $this->autoFilter->setParent($this);
27✔
3825
                } else {
3826
                    $this->{$key} = unserialize(serialize($val));
27✔
3827
                }
3828
            }
3829
        }
3830
    }
3831

3832
    /**
3833
     * Define the code name of the sheet.
3834
     *
3835
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3836
     *                       silently space to underscore)
3837
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3838
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3839
     *
3840
     * @return $this
3841
     */
3842
    public function setCodeName(string $codeName, bool $validate = true): static
11,419✔
3843
    {
3844
        // Is this a 'rename' or not?
3845
        if ($this->getCodeName() == $codeName) {
11,419✔
UNCOV
3846
            return $this;
×
3847
        }
3848

3849
        if ($validate) {
11,419✔
3850
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
11,419✔
3851

3852
            // Syntax check
3853
            // throw an exception if not valid
3854
            self::checkSheetCodeName($codeName);
11,419✔
3855

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

3858
            if ($this->parent !== null) {
11,419✔
3859
                // Is there already such sheet name?
3860
                if ($this->parent->sheetCodeNameExists($codeName)) {
11,378✔
3861
                    // Use name, but append with lowest possible integer
3862

3863
                    if (StringHelper::countCharacters($codeName) > 29) {
737✔
UNCOV
3864
                        $codeName = StringHelper::substring($codeName, 0, 29);
×
3865
                    }
3866
                    $i = 1;
737✔
3867
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
737✔
3868
                        ++$i;
300✔
3869
                        if ($i == 10) {
300✔
3870
                            if (StringHelper::countCharacters($codeName) > 28) {
2✔
UNCOV
3871
                                $codeName = StringHelper::substring($codeName, 0, 28);
×
3872
                            }
3873
                        } elseif ($i == 100) {
300✔
UNCOV
3874
                            if (StringHelper::countCharacters($codeName) > 27) {
×
UNCOV
3875
                                $codeName = StringHelper::substring($codeName, 0, 27);
×
3876
                            }
3877
                        }
3878
                    }
3879

3880
                    $codeName .= '_' . $i; // ok, we have a valid name
737✔
3881
                }
3882
            }
3883
        }
3884

3885
        $this->codeName = $codeName;
11,419✔
3886

3887
        return $this;
11,419✔
3888
    }
3889

3890
    /**
3891
     * Return the code name of the sheet.
3892
     */
3893
    public function getCodeName(): ?string
11,419✔
3894
    {
3895
        return $this->codeName;
11,419✔
3896
    }
3897

3898
    /**
3899
     * Sheet has a code name ?
3900
     */
3901
    public function hasCodeName(): bool
2✔
3902
    {
3903
        return $this->codeName !== null;
2✔
3904
    }
3905

3906
    public static function nameRequiresQuotes(string $sheetName): bool
4✔
3907
    {
3908
        return !Preg::isMatch(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName);
4✔
3909
    }
3910

3911
    public function isRowVisible(int $row): bool
130✔
3912
    {
3913
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
130✔
3914
    }
3915

3916
    /**
3917
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3918
     */
3919
    public function isCellLocked(string $coordinate): bool
1✔
3920
    {
3921
        if ($this->getProtection()->getsheet() !== true) {
1✔
3922
            return false;
1✔
3923
        }
3924
        if ($this->cellExists($coordinate)) {
1✔
3925
            return $this->getCell($coordinate)->isLocked();
1✔
3926
        }
3927
        $spreadsheet = $this->parent;
1✔
3928
        $xfIndex = $this->getXfIndex($coordinate);
1✔
3929
        if ($spreadsheet === null || $xfIndex === null) {
1✔
3930
            return true;
1✔
3931
        }
3932

UNCOV
3933
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
×
3934
    }
3935

3936
    /**
3937
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3938
     */
3939
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
1✔
3940
    {
3941
        if ($this->cellExists($coordinate)) {
1✔
3942
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
1✔
3943
        }
3944

3945
        // cell doesn't exist, therefore isn't a formula,
3946
        // therefore isn't hidden on formula bar.
3947
        return false;
1✔
3948
    }
3949

3950
    private function getXfIndex(string $coordinate): ?int
1✔
3951
    {
3952
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
1✔
3953
        $row = (int) $row;
1✔
3954
        $xfIndex = null;
1✔
3955
        if ($this->rowDimensionExists($row)) {
1✔
UNCOV
3956
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
×
3957
        }
3958
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
1✔
UNCOV
3959
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
×
3960
        }
3961

3962
        return $xfIndex;
1✔
3963
    }
3964

3965
    private string $backgroundImage = '';
3966

3967
    private string $backgroundMime = '';
3968

3969
    private string $backgroundExtension = '';
3970

3971
    public function getBackgroundImage(): string
1,095✔
3972
    {
3973
        return $this->backgroundImage;
1,095✔
3974
    }
3975

3976
    public function getBackgroundMime(): string
444✔
3977
    {
3978
        return $this->backgroundMime;
444✔
3979
    }
3980

3981
    public function getBackgroundExtension(): string
444✔
3982
    {
3983
        return $this->backgroundExtension;
444✔
3984
    }
3985

3986
    /**
3987
     * Set background image.
3988
     * Used on read/write for Xlsx.
3989
     * Used on write for Html.
3990
     *
3991
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3992
     */
3993
    public function setBackgroundImage(string $backgroundImage): self
4✔
3994
    {
3995
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
4✔
3996
        $mime = $imageArray['mime'];
4✔
3997
        if ($mime !== '') {
4✔
3998
            $extension = explode('/', $mime);
3✔
3999
            $extension = $extension[1];
3✔
4000
            $this->backgroundImage = $backgroundImage;
3✔
4001
            $this->backgroundMime = $mime;
3✔
4002
            $this->backgroundExtension = $extension;
3✔
4003
        }
4004

4005
        return $this;
4✔
4006
    }
4007

4008
    /**
4009
     * Copy cells, adjusting relative cell references in formulas.
4010
     * Acts similarly to Excel "fill handle" feature.
4011
     *
4012
     * @param string $fromCell Single source cell, e.g. C3
4013
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
4014
     * @param bool $copyStyle Copy styles as well as values, defaults to true
4015
     */
4016
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
1✔
4017
    {
4018
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
1✔
4019
        $valueString = $this->getCell($fromCell)->getValueString();
1✔
4020
        /** @var mixed[][] */
4021
        $style = $this->getStyle($fromCell)->exportArray();
1✔
4022
        $fromIndexes = Coordinate::indexesFromString($fromCell);
1✔
4023
        $referenceHelper = ReferenceHelper::getInstance();
1✔
4024
        foreach ($toArray as $destination) {
1✔
4025
            if ($destination !== $fromCell) {
1✔
4026
                $toIndexes = Coordinate::indexesFromString($destination);
1✔
4027
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
1✔
4028
                if ($copyStyle) {
1✔
4029
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
1✔
4030
                }
4031
            }
4032
        }
4033
    }
4034

4035
    public function calculateArrays(bool $preCalculateFormulas = true): void
1,288✔
4036
    {
4037
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
1,288✔
4038
            $keys = $this->cellCollection->getCoordinates();
52✔
4039
            foreach ($keys as $key) {
52✔
4040
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
52✔
4041
                    if (!Preg::isMatch(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValueString())) {
48✔
4042
                        $this->getCell($key)->getCalculatedValue();
47✔
4043
                    }
4044
                }
4045
            }
4046
        }
4047
    }
4048

4049
    public function isCellInSpillRange(string $coordinate): bool
2✔
4050
    {
4051
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
2✔
4052
            return false;
1✔
4053
        }
4054
        $this->calculateArrays();
1✔
4055
        $keys = $this->cellCollection->getCoordinates();
1✔
4056
        foreach ($keys as $key) {
1✔
4057
            $attributes = $this->getCell($key)->getFormulaAttributes();
1✔
4058
            if (isset($attributes['ref'])) {
1✔
4059
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
1✔
4060
                    // false for first cell in range, true otherwise
4061
                    return $coordinate !== $key;
1✔
4062
                }
4063
            }
4064
        }
4065

4066
        return false;
1✔
4067
    }
4068

4069
    /** @param mixed[][] $styleArray */
4070
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
2✔
4071
    {
4072
        $spreadsheet = $this->parent;
2✔
4073
        if ($spreadsheet === null) {
2✔
4074
            return false;
1✔
4075
        }
4076
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
1✔
4077
        $originalSelected = $this->selectedCells;
1✔
4078
        $this->getStyle($coordinate)->applyFromArray($styleArray);
1✔
4079
        $this->setSelectedCells($originalSelected);
1✔
4080
        if ($activeSheetIndex >= 0) {
1✔
4081
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
1✔
4082
        }
4083

4084
        return true;
1✔
4085
    }
4086

4087
    public function copyFormula(string $fromCell, string $toCell): void
1✔
4088
    {
4089
        $formula = $this->getCell($fromCell)->getValue();
1✔
4090
        $newFormula = $formula;
1✔
4091
        if (is_string($formula) && $this->getCell($fromCell)->getDataType() === DataType::TYPE_FORMULA) {
1✔
4092
            [$fromColInt, $fromRow] = Coordinate::indexesFromString($fromCell);
1✔
4093
            [$toColInt, $toRow] = Coordinate::indexesFromString($toCell);
1✔
4094
            $helper = ReferenceHelper::getInstance();
1✔
4095
            $newFormula = $helper->updateFormulaReferences(
1✔
4096
                $formula,
1✔
4097
                'A1',
1✔
4098
                $toColInt - $fromColInt,
1✔
4099
                $toRow - $fromRow
1✔
4100
            );
1✔
4101
        }
4102
        $this->setCellValue($toCell, $newFormula);
1✔
4103
    }
4104
}
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