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

PHPOffice / PhpSpreadsheet / 20985572567

14 Jan 2026 07:07AM UTC coverage: 96.201% (+0.2%) from 95.962%
20985572567

Pull #4657

github

web-flow
Merge c7ff53ab5 into 48f2fe37d
Pull Request #4657: Handling Unions as Function Arguments

11 of 12 new or added lines in 1 file covered. (91.67%)

359 existing lines in 16 files now uncovered.

46284 of 48112 relevant lines covered (96.2%)

386.88 hits per line

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

94.8
/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,194✔
325
    {
326
        // Set parent and title
327
        $this->parent = $parent;
11,194✔
328
        $this->setTitle($title, false);
11,194✔
329
        // setTitle can change $pTitle
330
        $this->setCodeName($this->getTitle());
11,194✔
331
        $this->setSheetState(self::SHEETSTATE_VISIBLE);
11,194✔
332

333
        $this->cellCollection = CellsFactory::getInstance($this);
11,194✔
334
        // Set page setup
335
        $this->pageSetup = new PageSetup();
11,194✔
336
        // Set page margins
337
        $this->pageMargins = new PageMargins();
11,194✔
338
        // Set page header/footer
339
        $this->headerFooter = new HeaderFooter();
11,194✔
340
        // Set sheet view
341
        $this->sheetView = new SheetView();
11,194✔
342
        // Drawing collection
343
        $this->drawingCollection = new ArrayObject();
11,194✔
344
        // In Cell Drawing collection
345
        $this->inCellDrawingCollection = new ArrayObject();
11,194✔
346
        // Chart collection
347
        $this->chartCollection = new ArrayObject();
11,194✔
348
        // Protection
349
        $this->protection = new Protection();
11,194✔
350
        // Default row dimension
351
        $this->defaultRowDimension = new RowDimension(null);
11,194✔
352
        // Default column dimension
353
        $this->defaultColumnDimension = new ColumnDimension(null);
11,194✔
354
        // AutoFilter
355
        $this->autoFilter = new AutoFilter('', $this);
11,194✔
356
        // Table collection
357
        $this->tableCollection = new ArrayObject();
11,194✔
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,220✔
365
    {
366
        if (isset($this->cellCollection)) { //* @phpstan-ignore-line
10,220✔
367
            $this->cellCollection->unsetWorksheetCells();
10,220✔
368
            unset($this->cellCollection);
10,220✔
369
        }
370
        //    detach ourself from the workbook, so that it can then delete this worksheet successfully
371
        $this->parent = null;
10,220✔
372
    }
373

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

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

386
    /**
387
     * Return the cell collection.
388
     */
389
    public function getCellCollection(): Cells
10,783✔
390
    {
391
        return $this->cellCollection;
10,783✔
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,194✔
412
    {
413
        $charCount = StringHelper::countCharacters($sheetCodeName);
11,194✔
414
        if ($charCount == 0) {
11,194✔
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,194✔
420
            || (StringHelper::substring($sheetCodeName, -1, 1) == '\'')
11,194✔
421
            || (StringHelper::substring($sheetCodeName, 0, 1) == '\'')
11,194✔
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,194✔
428
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
1✔
429
        }
430

431
        return $sheetCodeName;
11,194✔
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,194✔
442
    {
443
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ]
444
        if (str_replace(self::INVALID_CHARACTERS, '', $sheetTitle) !== $sheetTitle) {
11,194✔
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,194✔
450
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
4✔
451
        }
452

453
        return $sheetTitle;
11,194✔
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,580✔
464
    {
465
        if (!isset($this->cellCollection)) { //* @phpstan-ignore-line
1,580✔
466
            return [];
1✔
467
        }
468

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

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

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

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

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

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

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

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

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

531
    /**
532
     * Get collection of drawings.
533
     *
534
     * @return ArrayObject<int, BaseDrawing>
535
     */
536
    public function getInCellDrawingCollection(): ArrayObject
439✔
537
    {
538
        return $this->inCellDrawingCollection;
439✔
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✔
UNCOV
580
            return false;
×
581
        }
582
        if ($index === null) {
79✔
UNCOV
583
            $index = --$chartCount;
×
584
        }
585
        if (!isset($this->chartCollection[$index])) {
79✔
UNCOV
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
524✔
675
    {
676
        // Return
677
        return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
524✔
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
576✔
686
    {
687
        // Return
688
        return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
576✔
689
    }
690

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

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

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

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

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

729
                    //By default merged cells should be ignored
730
                    $isMergedButProceed = false;
65✔
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()) {
65✔
UNCOV
734
                        $range = (string) $cell->getMergeRange();
×
UNCOV
735
                        $rangeBoundaries = Coordinate::rangeDimension($range);
×
UNCOV
736
                        if ($rangeBoundaries[0] === 1) {
×
UNCOV
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) {
65✔
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;
65✔
746
                        if (!empty($autoFilterIndentRanges)) {
65✔
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();
65✔
758
                        $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER);
65✔
759

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

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

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

803
        return $this;
824✔
804
    }
805

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

814
    /**
815
     * Get parent, throw exception if null.
816
     */
817
    public function getParentOrThrow(): Spreadsheet
10,864✔
818
    {
819
        if ($this->parent !== null) {
10,864✔
820
            return $this->parent;
10,863✔
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✔
UNCOV
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
7✔
849
    {
850
        $this->parent = $parent;
7✔
851

852
        return $this;
7✔
853
    }
854

855
    /**
856
     * Get title.
857
     */
858
    public function getTitle(): string
11,194✔
859
    {
860
        return $this->title;
11,194✔
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,194✔
878
    {
879
        // Is this a 'rename' or not?
880
        if ($this->getTitle() == $title) {
11,194✔
881
            return $this;
320✔
882
        }
883

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

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

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

896
                    if (StringHelper::countCharacters($title) > 29) {
2✔
UNCOV
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✔
UNCOV
903
                            if (StringHelper::countCharacters($title) > 28) {
×
UNCOV
904
                                $title = StringHelper::substring($title, 0, 28);
×
905
                            }
906
                        } elseif ($i == 100) {
1✔
UNCOV
907
                            if (StringHelper::countCharacters($title) > 27) {
×
UNCOV
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,194✔
920

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

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

934
    /**
935
     * Get sheet state.
936
     *
937
     * @return string Sheet state (visible, hidden, veryHidden)
938
     */
939
    public function getSheetState(): string
560✔
940
    {
941
        return $this->sheetState;
560✔
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,194✔
952
    {
953
        $this->sheetState = $value;
11,194✔
954

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

958
    /**
959
     * Get page setup.
960
     */
961
    public function getPageSetup(): PageSetup
1,693✔
962
    {
963
        return $this->pageSetup;
1,693✔
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,693✔
982
    {
983
        return $this->pageMargins;
1,693✔
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
638✔
1002
    {
1003
        return $this->headerFooter;
638✔
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
669✔
1022
    {
1023
        return $this->sheetView;
669✔
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
689✔
1042
    {
1043
        return $this->protection;
689✔
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,595✔
1067
    {
1068
        if ($row === null) {
1,595✔
1069
            return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
1,594✔
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
783✔
1084
    {
1085
        return $this->cellCollection->getHighestColumn($row);
783✔
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,061✔
1097
    {
1098
        if ($column === null) {
1,061✔
1099
            return $this->cachedHighestRow;
1,060✔
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
784✔
1114
    {
1115
        return $this->cellCollection->getHighestRow($column);
784✔
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,062✔
1139
    {
1140
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
5,062✔
1141
        $this->getCell($cellAddress)->setValue($value, $binder);
5,062✔
1142

1143
        return $this;
5,062✔
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
118✔
1164
    {
1165
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
118✔
1166
        $this->getCell($cellAddress)->setValueExplicit($value, $dataType);
118✔
1167

1168
        return $this;
118✔
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,723✔
1185
    {
1186
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
10,723✔
1187

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

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

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

1200
        return $cell ?? $sheet->createNewCell($finalCoordinate);
10,723✔
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,747✔
1210
    {
1211
        $sheet = null;
10,747✔
1212
        $finalCoordinate = null;
10,747✔
1213

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

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

UNCOV
1221
            if ($sheet === null) {
×
UNCOV
1222
                throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
×
1223
            }
1224
        } elseif (
1225
            !Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate)
10,747✔
1226
            && Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate)
10,747✔
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✔
UNCOV
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,747✔
1243
            $sheet = $this;
10,747✔
1244
            $finalCoordinate = strtoupper($coordinate);
10,747✔
1245
        }
1246

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

1252
        return [$sheet, $finalCoordinate];
10,747✔
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
65✔
1263
    {
1264
        // Check cell collection
1265
        if ($this->cellCollection->has($coordinate)) {
65✔
1266
            return $this->cellCollection->get($coordinate);
65✔
1267
        }
1268

UNCOV
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,723✔
1285
    {
1286
        [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate);
10,723✔
1287
        $cell = new Cell(null, DataType::TYPE_NULL, $this);
10,723✔
1288
        $this->cellCollection->add($coordinate, $cell);
10,723✔
1289

1290
        // Coordinates
1291
        if ($column > $this->cachedHighestColumn) {
10,723✔
1292
            $this->cachedHighestColumn = $column;
7,403✔
1293
        }
1294
        if ($row > $this->cachedHighestRow) {
10,723✔
1295
            $this->cachedHighestRow = $row;
8,831✔
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,723✔
1301
        $columnDimension = $this->columnDimensions[$columnString] ?? null;
10,723✔
1302

1303
        $xfSet = false;
10,723✔
1304
        if ($rowDimension !== null) {
10,723✔
1305
            $rowXf = (int) $rowDimension->getXfIndex();
415✔
1306
            if ($rowXf > 0) {
415✔
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,723✔
1313
            $colXf = (int) $columnDimension->getXfIndex();
588✔
1314
            if ($colXf > 0) {
588✔
1315
                // then there is a column dimension, assign it to the cell
1316
                $cell->setXfIndex($colXf);
217✔
1317
            }
1318
        }
1319

1320
        return $cell;
10,723✔
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,667✔
1330
    {
1331
        $cellAddress = Validations::validateCellAddress($coordinate);
10,667✔
1332
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
10,667✔
1333

1334
        return $sheet->getCellCollection()->has($finalCoordinate);
10,667✔
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
622✔
1343
    {
1344
        // Get row dimension
1345
        if (!isset($this->rowDimensions[$row])) {
622✔
1346
            $this->rowDimensions[$row] = new RowDimension($row);
622✔
1347

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

1351
        return $this->rowDimensions[$row];
622✔
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
677✔
1362
    {
1363
        return isset($this->rowDimensions[$row]);
677✔
1364
    }
1365

1366
    public function columnDimensionExists(string $column): bool
42✔
1367
    {
1368
        return isset($this->columnDimensions[$column]);
42✔
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
686✔
1377
    {
1378
        // Uppercase coordinate
1379
        $column = strtoupper($column);
686✔
1380

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

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

1391
        return $this->columnDimensions[$column];
686✔
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
114✔
1400
    {
1401
        return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
114✔
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,692✔
1420
    {
1421
        if (is_string($cellCoordinate)) {
10,692✔
1422
            $cellCoordinate = Validations::definedNameToCoordinate($cellCoordinate, $this);
10,690✔
1423
        }
1424
        $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate);
10,692✔
1425
        $cellCoordinate = str_replace('$', '', $cellCoordinate);
10,692✔
1426

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

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

1433
        return $this->getParentOrThrow()->getCellXfSupervisor();
10,692✔
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
809✔
1502
    {
1503
        $coordinate = strtoupper($coordinate);
809✔
1504
        if (Preg::isMatch('/[: ,]/', $coordinate)) {
809✔
1505
            return $this->conditionalStylesCollection[$coordinate] ?? [];
49✔
1506
        }
1507

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

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

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

1540
        return $outArray;
611✔
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✔
UNCOV
1548
            return 0;
×
1549
        }
1550
        if ($a === 0) {
1✔
UNCOV
1551
            return 1;
×
1552
        }
1553
        if ($b === 0) {
1✔
UNCOV
1554
            return -1;
×
1555
        }
1556

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

1560
    public function getConditionalRange(string $coordinate): ?string
189✔
1561
    {
1562
        $coordinate = strtoupper($coordinate);
189✔
1563
        $cell = $this->getCell($coordinate);
189✔
1564
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
189✔
1565
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
189✔
1566
            foreach ($cellBlocks as $cellBlock) {
189✔
1567
                if ($cell->isInRange($cellBlock)) {
189✔
1568
                    return $conditionalRange;
188✔
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,416✔
1610
    {
1611
        return $this->conditionalStylesCollection;
1,416✔
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
345✔
1623
    {
1624
        $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
345✔
1625

1626
        return $this;
345✔
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✔
UNCOV
1657
            $tmp = $rangeStart;
×
UNCOV
1658
            $rangeStart = $rangeEnd;
×
UNCOV
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✔
UNCOV
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✔
UNCOV
1695
            $tmp = $rangeStart;
×
UNCOV
1696
            $rangeStart = $rangeEnd;
×
UNCOV
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
692✔
1740
    {
1741
        $breaks = [];
692✔
1742
        /** @var callable $compareFunction */
1743
        $compareFunction = [self::class, 'compareRowBreaks'];
692✔
1744
        uksort($this->rowBreaks, $compareFunction);
692✔
1745
        foreach ($this->rowBreaks as $break) {
692✔
1746
            $breaks[$break->getCoordinate()] = self::BREAK_ROW;
10✔
1747
        }
1748
        /** @var callable $compareFunction */
1749
        $compareFunction = [self::class, 'compareColumnBreaks'];
692✔
1750
        uksort($this->columnBreaks, $compareFunction);
692✔
1751
        foreach ($this->columnBreaks as $break) {
692✔
1752
            $breaks[$break->getCoordinate()] = self::BREAK_COLUMN;
8✔
1753
        }
1754

1755
        return $breaks;
692✔
1756
    }
1757

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

1769
        return $this->rowBreaks;
584✔
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
583✔
1794
    {
1795
        /** @var callable $compareFunction */
1796
        $compareFunction = [self::class, 'compareColumnBreaks'];
583✔
1797
        uksort($this->columnBreaks, $compareFunction);
583✔
1798

1799
        return $this->columnBreaks;
583✔
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
178✔
1817
    {
1818
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
178✔
1819

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

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

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

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

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

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

1857
        return $this;
169✔
1858
    }
1859

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

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

1878
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
18✔
UNCOV
1879
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
×
1880
        }
1881
    }
1882

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

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

1902
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
41✔
1903
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
4✔
1904
        }
1905
    }
1906

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

1925
        return $leftCellValue;
59✔
1926
    }
1927

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

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

1951
        return $this;
22✔
1952
    }
1953

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

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

1976
        return $this;
126✔
1977
    }
1978

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

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

1999
        return $this;
28✔
2000
    }
2001

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

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

2021
        return $this;
21✔
2022
    }
2023

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

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

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

2059
            $this->autoFilter->setRange($cellRange);
21✔
2060
        }
2061

2062
        return $this;
21✔
2063
    }
2064

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

2072
        return $this;
1✔
2073
    }
2074

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

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

2095
        return $this;
105✔
2096
    }
2097

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

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

2110
        return $tableNames;
1✔
2111
    }
2112

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

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

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

2140
        return null;
41✔
2141
    }
2142

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

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

2158
        return $this;
1✔
2159
    }
2160

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

2168
        return $this;
1✔
2169
    }
2170

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

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

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

2220
        $topLeftCell = "$topLeftCell";
49✔
2221
        $this->paneTopLeftCell = $topLeftCell;
49✔
2222

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

2243
        return $this;
49✔
2244
    }
2245

2246
    public function setTopLeftCell(string $topLeftCell): self
59✔
2247
    {
2248
        $this->topLeftCell = $topLeftCell;
59✔
2249

2250
        return $this;
59✔
2251
    }
2252

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

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

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

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

2280
        return $this;
26✔
2281
    }
2282

2283
    public function usesPanes(): bool
506✔
2284
    {
2285
        return $this->xSplit > 0 || $this->ySplit > 0;
506✔
2286
    }
2287

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

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

2299
        return $this;
46✔
2300
    }
2301

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

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

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

2317
        return $this;
49✔
2318
    }
2319

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

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

2332
        return $this;
11✔
2333
    }
2334

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

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

2347
        return $this;
26✔
2348
    }
2349

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

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

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

2370
        return $this;
26✔
2371
    }
2372

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

2390
        return $this;
42✔
2391
    }
2392

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

2410
        return $this;
49✔
2411
    }
2412

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

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

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

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

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

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

2498
        $this->rowDimensions = $holdRowDimensions;
52✔
2499

2500
        return $this;
52✔
2501
    }
2502

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

2520
        return $holdRowDimensions;
52✔
2521
    }
2522

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

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

2578
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
42✔
2579

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

2584
        $this->columnDimensions = $holdColumnDimensions;
42✔
2585

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

2590
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
33✔
2591

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

2597
        $this->garbageCollect();
33✔
2598

2599
        return $this;
33✔
2600
    }
2601

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

2620
        return $holdColumnDimensions;
42✔
2621
    }
2622

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

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

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

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

2659
        return $this;
903✔
2660
    }
2661

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

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

2681
        return $this;
589✔
2682
    }
2683

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

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

2703
        return $this;
434✔
2704
    }
2705

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

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

2725
        return $this;
434✔
2726
    }
2727

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

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

2747
        return $this;
434✔
2748
    }
2749

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

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

2771
        return $this;
126✔
2772
    }
2773

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

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

2798
        return $this;
55✔
2799
    }
2800

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

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

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

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

2830
        return $newComment;
116✔
2831
    }
2832

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

2843
    /**
2844
     * Get selected cells.
2845
     */
2846
    public function getSelectedCells(): string
10,808✔
2847
    {
2848
        return $this->selectedCells;
10,808✔
2849
    }
2850

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

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

2879
        if (Coordinate::coordinateIsRange($coordinate)) {
10,757✔
2880
            [$first] = Coordinate::splitRange($coordinate);
519✔
2881
            $this->activeCell = $first[0];
519✔
2882
        } else {
2883
            $this->activeCell = $coordinate;
10,726✔
2884
        }
2885
        $this->selectedCells = $coordinate;
10,757✔
2886
        $this->setSelectedCellsActivePane();
10,757✔
2887

2888
        return $this;
10,757✔
2889
    }
2890

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

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

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

2929
        return $this;
163✔
2930
    }
2931

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

2950
        // start coordinate
2951
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
862✔
2952
        $startRow = (int) $startRow;
862✔
2953

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

2980
        return $this;
862✔
2981
    }
2982

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

2996
        if ($cell->getValue() !== null) {
186✔
2997
            if ($cell->getValue() instanceof RichText) {
186✔
2998
                $returnValue = $cell->getValue()->getPlainText();
4✔
2999
            } else {
3000
                $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue();
186✔
3001
            }
3002

3003
            if ($formatData) {
186✔
3004
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
122✔
3005
                /** @var null|bool|float|int|RichText|string */
3006
                $returnValuex = $returnValue;
122✔
3007
                $returnValue = NumberFormat::toFormattedString(
122✔
3008
                    $returnValuex,
122✔
3009
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL,
122✔
3010
                    lessFloatPrecision: $lessFloatPrecision
122✔
3011
                );
122✔
3012
            }
3013
        }
3014

3015
        return $returnValue;
186✔
3016
    }
3017

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

3045
        // Loop through rows
3046
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision) as $rowRef => $rowArray) {
154✔
3047
            /** @var int $rowRef */
3048
            $returnValue[$rowRef] = $rowArray;
154✔
3049
        }
3050

3051
        // Return
3052
        return $returnValue;
154✔
3053
    }
3054

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

3082
        $parts = explode(',', $ranges);
3✔
3083
        foreach ($parts as $part) {
3✔
3084
            // Loop through rows
3085
            foreach ($this->rangeToArrayYieldRows($part, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision) as $rowRef => $rowArray) {
3✔
3086
                /** @var int $rowRef */
3087
                $returnValue[$rowRef] = $rowArray;
3✔
3088
            }
3089
        }
3090

3091
        // Return
3092
        return $returnValue;
3✔
3093
    }
3094

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

3122
        //    Identify the range that we need to extract from the worksheet
3123
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
186✔
3124
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
186✔
3125
        $minRow = $rangeStart[1];
186✔
3126
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
186✔
3127
        $maxRow = $rangeEnd[1];
186✔
3128
        $minColInt = $rangeStart[0];
186✔
3129
        $maxColInt = $rangeEnd[0];
186✔
3130

3131
        StringHelper::stringIncrement($maxCol);
186✔
3132
        /** @var array<string, bool> */
3133
        $hiddenColumns = [];
186✔
3134
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
186✔
3135
        $hideColumns = !empty($hiddenColumns);
186✔
3136

3137
        $keys = $this->cellCollection->getSortedCoordinatesInt();
186✔
3138
        $keyIndex = 0;
186✔
3139
        $keysCount = count($keys);
186✔
3140
        // Loop through rows
3141
        for ($row = $minRow; $row <= $maxRow; ++$row) {
186✔
3142
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
186✔
3143
                continue;
4✔
3144
            }
3145
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
186✔
3146
            $returnValue = $nullRow;
186✔
3147

3148
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
186✔
3149
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
186✔
3150

3151
            // Binary search to quickly approach the correct index
3152
            $keyIndex = intdiv($keysCount, 2);
186✔
3153
            $boundLow = 0;
186✔
3154
            $boundHigh = $keysCount - 1;
186✔
3155
            while ($boundLow <= $boundHigh) {
186✔
3156
                $keyIndex = intdiv($boundLow + $boundHigh, 2);
186✔
3157
                if ($keys[$keyIndex] < $index) {
186✔
3158
                    $boundLow = $keyIndex + 1;
154✔
3159
                } elseif ($keys[$keyIndex] > $index) {
186✔
3160
                    $boundHigh = $keyIndex - 1;
168✔
3161
                } else {
3162
                    break;
178✔
3163
                }
3164
            }
3165

3166
            // Realign to the proper index value
3167
            while ($keyIndex > 0 && $keys[$keyIndex] > $index) {
186✔
3168
                --$keyIndex;
14✔
3169
            }
3170
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
186✔
3171
                ++$keyIndex;
20✔
3172
            }
3173

3174
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
186✔
3175
                $key = $keys[$keyIndex];
186✔
3176
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
186✔
3177
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
186✔
3178
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
186✔
3179
                    $col = Coordinate::stringFromColumnIndex($thisCol);
186✔
3180
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
186✔
3181
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
186✔
3182
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
186✔
3183
                        if ($cell !== null) {
186✔
3184
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue, lessFloatPrecision: $lessFloatPrecision);
186✔
3185
                            if ($reduceArrays) {
186✔
3186
                                while (is_array($value)) {
21✔
3187
                                    $value = array_shift($value);
19✔
3188
                                }
3189
                            }
3190
                            if ($value !== $nullValue) {
186✔
3191
                                $returnValue[$columnRef] = $value;
186✔
3192
                            }
3193
                        }
3194
                    }
3195
                }
3196
                ++$keyIndex;
186✔
3197
            }
3198

3199
            yield $rowRef => $returnValue;
186✔
3200
        }
3201
    }
3202

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

3236
        return $nullRow;
186✔
3237
    }
3238

3239
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
19✔
3240
    {
3241
        $namedRange = DefinedName::resolveName($definedName, $this);
19✔
3242
        if ($namedRange === null) {
19✔
3243
            if ($returnNullIfInvalid) {
6✔
3244
                return null;
5✔
3245
            }
3246

3247
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
1✔
3248
        }
3249

3250
        if ($namedRange->isFormula()) {
13✔
UNCOV
3251
            if ($returnNullIfInvalid) {
×
UNCOV
3252
                return null;
×
3253
            }
3254

UNCOV
3255
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
×
3256
        }
3257

3258
        if ($namedRange->getLocalOnly()) {
13✔
3259
            $worksheet = $namedRange->getWorksheet();
2✔
3260
            if ($worksheet === null || $this !== $worksheet) {
2✔
UNCOV
3261
                if ($returnNullIfInvalid) {
×
UNCOV
3262
                    return null;
×
3263
                }
3264

UNCOV
3265
                throw new Exception(
×
UNCOV
3266
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
×
UNCOV
3267
                );
×
3268
            }
3269
        }
3270

3271
        return $namedRange;
13✔
3272
    }
3273

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

3311
        return $retVal;
1✔
3312
    }
3313

3314
    /**
3315
     * Create array from worksheet.
3316
     *
3317
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3318
     * @param bool $calculateFormulas Should formulas be calculated?
3319
     * @param bool $formatData Should formatting be applied to cell values?
3320
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3321
     *                             True - Return rows and columns indexed by their actual row and column IDs
3322
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3323
     *                            True - Don't return values for rows/columns that are defined as hidden.
3324
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3325
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3326
     *
3327
     * @return mixed[][]
3328
     */
3329
    public function toArray(
85✔
3330
        mixed $nullValue = null,
3331
        bool $calculateFormulas = true,
3332
        bool $formatData = true,
3333
        bool $returnCellRef = false,
3334
        bool $ignoreHidden = false,
3335
        bool $reduceArrays = false,
3336
        bool $lessFloatPrecision = false
3337
    ): array {
3338
        // Garbage collect...
3339
        $this->garbageCollect();
85✔
3340
        $this->calculateArrays($calculateFormulas);
85✔
3341

3342
        //    Identify the range that we need to extract from the worksheet
3343
        $maxCol = $this->getHighestColumn();
85✔
3344
        $maxRow = $this->getHighestRow();
85✔
3345

3346
        // Return
3347
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision);
85✔
3348
    }
3349

3350
    /**
3351
     * Get row iterator.
3352
     *
3353
     * @param int $startRow The row number at which to start iterating
3354
     * @param ?int $endRow The row number at which to stop iterating
3355
     */
3356
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
98✔
3357
    {
3358
        return new RowIterator($this, $startRow, $endRow);
98✔
3359
    }
3360

3361
    /**
3362
     * Get column iterator.
3363
     *
3364
     * @param string $startColumn The column address at which to start iterating
3365
     * @param ?string $endColumn The column address at which to stop iterating
3366
     */
3367
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
26✔
3368
    {
3369
        return new ColumnIterator($this, $startColumn, $endColumn);
26✔
3370
    }
3371

3372
    /**
3373
     * Run PhpSpreadsheet garbage collector.
3374
     *
3375
     * @return $this
3376
     */
3377
    public function garbageCollect(): static
1,259✔
3378
    {
3379
        // Flush cache
3380
        $this->cellCollection->get('A1');
1,259✔
3381

3382
        // Lookup highest column and highest row if cells are cleaned
3383
        $colRow = $this->cellCollection->getHighestRowAndColumn();
1,259✔
3384
        $highestRow = $colRow['row'];
1,259✔
3385
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
1,259✔
3386

3387
        // Loop through column dimensions
3388
        foreach ($this->columnDimensions as $dimension) {
1,259✔
3389
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
181✔
3390
        }
3391

3392
        // Loop through row dimensions
3393
        foreach ($this->rowDimensions as $dimension) {
1,259✔
3394
            $highestRow = max($highestRow, $dimension->getRowIndex());
121✔
3395
        }
3396

3397
        // Cache values
3398
        $this->cachedHighestColumn = max(1, $highestColumn);
1,259✔
3399
        /** @var int $highestRow */
3400
        $this->cachedHighestRow = $highestRow;
1,259✔
3401

3402
        // Return
3403
        return $this;
1,259✔
3404
    }
3405

3406
    /**
3407
     * @deprecated 5.2.0 Serves no useful purpose. No replacement.
3408
     *
3409
     * @codeCoverageIgnore
3410
     */
3411
    public function getHashInt(): int
3412
    {
3413
        return spl_object_id($this);
3414
    }
3415

3416
    /**
3417
     * Extract worksheet title from range.
3418
     *
3419
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3420
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3421
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3422
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3423
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3424
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3425
     *
3426
     * @param ?string $range Range to extract title from
3427
     * @param bool $returnRange Return range? (see example)
3428
     *
3429
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3430
     */
3431
    public static function extractSheetTitle(?string $range, bool $returnRange = false, bool $unapostrophize = false): array|null|string
10,985✔
3432
    {
3433
        if (empty($range)) {
10,985✔
3434
            return $returnRange ? [null, null] : null;
13✔
3435
        }
3436

3437
        // Sheet title included?
3438
        if (($sep = strrpos($range, '!')) === false) {
10,983✔
3439
            return $returnRange ? ['', $range] : '';
10,954✔
3440
        }
3441

3442
        if ($returnRange) {
1,456✔
3443
            $title = substr($range, 0, $sep);
1,456✔
3444
            if ($unapostrophize) {
1,456✔
3445
                $title = self::unApostrophizeTitle($title);
1,396✔
3446
            }
3447

3448
            return [$title, substr($range, $sep + 1)];
1,456✔
3449
        }
3450

3451
        return substr($range, $sep + 1);
7✔
3452
    }
3453

3454
    public static function unApostrophizeTitle(?string $title): string
1,410✔
3455
    {
3456
        $title ??= '';
1,410✔
3457
        if (str_starts_with($title, "'") && str_ends_with($title, "'")) {
1,410✔
3458
            $title = str_replace("''", "'", substr($title, 1, -1));
1,335✔
3459
        }
3460

3461
        return $title;
1,410✔
3462
    }
3463

3464
    /**
3465
     * Get hyperlink.
3466
     *
3467
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3468
     */
3469
    public function getHyperlink(string $cellCoordinate): Hyperlink
106✔
3470
    {
3471
        $this->getCell($cellCoordinate)->setHadHyperlink(true);
106✔
3472
        // return hyperlink if we already have one
3473
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
106✔
3474
            return $this->hyperlinkCollection[$cellCoordinate];
56✔
3475
        }
3476

3477
        // else create hyperlink
3478
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
106✔
3479

3480
        return $this->hyperlinkCollection[$cellCoordinate];
106✔
3481
    }
3482

3483
    /**
3484
     * Set hyperlink.
3485
     *
3486
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3487
     *
3488
     * @return $this
3489
     */
3490
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null, bool $reset = true): static
584✔
3491
    {
3492
        if ($hyperlink === null) {
584✔
3493
            unset($this->hyperlinkCollection[$cellCoordinate]);
583✔
3494
            if ($reset) {
583✔
3495
                $this->getCell($cellCoordinate)
549✔
3496
                    ->setHadHyperlink(false);
549✔
3497
            }
3498
        } else {
3499
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
36✔
3500
            $this->getCell($cellCoordinate)->setHadHyperlink(true);
36✔
3501
        }
3502

3503
        return $this;
584✔
3504
    }
3505

3506
    /**
3507
     * Hyperlink at a specific coordinate exists?
3508
     *
3509
     * @param string $coordinate eg: 'A1'
3510
     */
3511
    public function hyperlinkExists(string $coordinate): bool
651✔
3512
    {
3513
        return isset($this->hyperlinkCollection[$coordinate]);
651✔
3514
    }
3515

3516
    /**
3517
     * Get collection of hyperlinks.
3518
     *
3519
     * @return Hyperlink[]
3520
     */
3521
    public function getHyperlinkCollection(): array
688✔
3522
    {
3523
        return $this->hyperlinkCollection;
688✔
3524
    }
3525

3526
    /**
3527
     * Get data validation.
3528
     *
3529
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3530
     */
3531
    public function getDataValidation(string $cellCoordinate): DataValidation
37✔
3532
    {
3533
        // return data validation if we already have one
3534
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
37✔
3535
            return $this->dataValidationCollection[$cellCoordinate];
28✔
3536
        }
3537

3538
        // or if cell is part of a data validation range
3539
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
28✔
3540
            $keyParts = explode(' ', $key);
12✔
3541
            foreach ($keyParts as $keyPart) {
12✔
3542
                if ($keyPart === $cellCoordinate) {
12✔
3543
                    return $dataValidation;
1✔
3544
                }
3545
                if (str_contains($keyPart, ':')) {
12✔
3546
                    if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) {
9✔
3547
                        return $dataValidation;
9✔
3548
                    }
3549
                }
3550
            }
3551
        }
3552

3553
        // else create data validation
3554
        $dataValidation = new DataValidation();
20✔
3555
        $dataValidation->setSqref($cellCoordinate);
20✔
3556
        $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
20✔
3557

3558
        return $dataValidation;
20✔
3559
    }
3560

3561
    /**
3562
     * Set data validation.
3563
     *
3564
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3565
     *
3566
     * @return $this
3567
     */
3568
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
92✔
3569
    {
3570
        if ($dataValidation === null) {
92✔
3571
            unset($this->dataValidationCollection[$cellCoordinate]);
59✔
3572
        } else {
3573
            $dataValidation->setSqref($cellCoordinate);
40✔
3574
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
40✔
3575
        }
3576

3577
        return $this;
92✔
3578
    }
3579

3580
    /**
3581
     * Data validation at a specific coordinate exists?
3582
     *
3583
     * @param string $coordinate eg: 'A1'
3584
     */
3585
    public function dataValidationExists(string $coordinate): bool
25✔
3586
    {
3587
        if (isset($this->dataValidationCollection[$coordinate])) {
25✔
3588
            return true;
23✔
3589
        }
3590
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
8✔
3591
            $keyParts = explode(' ', $key);
7✔
3592
            foreach ($keyParts as $keyPart) {
7✔
3593
                if ($keyPart === $coordinate) {
7✔
3594
                    return true;
1✔
3595
                }
3596
                if (str_contains($keyPart, ':')) {
7✔
3597
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
2✔
3598
                        return true;
2✔
3599
                    }
3600
                }
3601
            }
3602
        }
3603

3604
        return false;
6✔
3605
    }
3606

3607
    /**
3608
     * Get collection of data validations.
3609
     *
3610
     * @return DataValidation[]
3611
     */
3612
    public function getDataValidationCollection(): array
689✔
3613
    {
3614
        $collectionCells = [];
689✔
3615
        $collectionRanges = [];
689✔
3616
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
689✔
3617
            if (Preg::isMatch('/[: ]/', $key)) {
27✔
3618
                $collectionRanges[$key] = $dataValidation;
15✔
3619
            } else {
3620
                $collectionCells[$key] = $dataValidation;
22✔
3621
            }
3622
        }
3623

3624
        return array_merge($collectionCells, $collectionRanges);
689✔
3625
    }
3626

3627
    /**
3628
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3629
     *
3630
     * @return string Adjusted range value
3631
     */
UNCOV
3632
    public function shrinkRangeToFit(string $range): string
×
3633
    {
UNCOV
3634
        $maxCol = $this->getHighestColumn();
×
UNCOV
3635
        $maxRow = $this->getHighestRow();
×
UNCOV
3636
        $maxCol = Coordinate::columnIndexFromString($maxCol);
×
3637

UNCOV
3638
        $rangeBlocks = explode(' ', $range);
×
UNCOV
3639
        foreach ($rangeBlocks as &$rangeSet) {
×
UNCOV
3640
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
×
3641

UNCOV
3642
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
×
UNCOV
3643
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3644
            }
UNCOV
3645
            if ($rangeBoundaries[0][1] > $maxRow) {
×
UNCOV
3646
                $rangeBoundaries[0][1] = $maxRow;
×
3647
            }
UNCOV
3648
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
×
3649
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3650
            }
UNCOV
3651
            if ($rangeBoundaries[1][1] > $maxRow) {
×
UNCOV
3652
                $rangeBoundaries[1][1] = $maxRow;
×
3653
            }
UNCOV
3654
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
×
3655
        }
UNCOV
3656
        unset($rangeSet);
×
3657

UNCOV
3658
        return implode(' ', $rangeBlocks);
×
3659
    }
3660

3661
    /**
3662
     * Get tab color.
3663
     */
3664
    public function getTabColor(): Color
23✔
3665
    {
3666
        if ($this->tabColor === null) {
23✔
3667
            $this->tabColor = new Color();
23✔
3668
        }
3669

3670
        return $this->tabColor;
23✔
3671
    }
3672

3673
    /**
3674
     * Reset tab color.
3675
     *
3676
     * @return $this
3677
     */
3678
    public function resetTabColor(): static
1✔
3679
    {
3680
        $this->tabColor = null;
1✔
3681

3682
        return $this;
1✔
3683
    }
3684

3685
    /**
3686
     * Tab color set?
3687
     */
3688
    public function isTabColorSet(): bool
582✔
3689
    {
3690
        return $this->tabColor !== null;
582✔
3691
    }
3692

3693
    /**
3694
     * Copy worksheet (!= clone!).
3695
     */
UNCOV
3696
    public function copy(): static
×
3697
    {
UNCOV
3698
        return clone $this;
×
3699
    }
3700

3701
    /**
3702
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3703
     *          exist in the collection for this row. false will be returned otherwise.
3704
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3705
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3706
     *                  cells, then the row will be considered empty.
3707
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3708
     *                  string value cells, then the row will be considered empty.
3709
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3710
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3711
     *                  will be considered empty.
3712
     *
3713
     * @param int $definitionOfEmptyFlags
3714
     *              Possible Flag Values are:
3715
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3716
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3717
     */
3718
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
9✔
3719
    {
3720
        try {
3721
            $iterator = new RowIterator($this, $rowId, $rowId);
9✔
3722
            $iterator->seek($rowId);
8✔
3723
            $row = $iterator->current();
8✔
3724
        } catch (Exception) {
1✔
3725
            return true;
1✔
3726
        }
3727

3728
        return $row->isEmpty($definitionOfEmptyFlags);
8✔
3729
    }
3730

3731
    /**
3732
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3733
     *          exist in the collection for this column. false will be returned otherwise.
3734
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3735
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3736
     *                  cells, then the column will be considered empty.
3737
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3738
     *                  string value cells, then the column will be considered empty.
3739
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3740
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3741
     *                  will be considered empty.
3742
     *
3743
     * @param int $definitionOfEmptyFlags
3744
     *              Possible Flag Values are:
3745
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3746
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3747
     */
3748
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
9✔
3749
    {
3750
        try {
3751
            $iterator = new ColumnIterator($this, $columnId, $columnId);
9✔
3752
            $iterator->seek($columnId);
8✔
3753
            $column = $iterator->current();
8✔
3754
        } catch (Exception) {
1✔
3755
            return true;
1✔
3756
        }
3757

3758
        return $column->isEmpty($definitionOfEmptyFlags);
8✔
3759
    }
3760

3761
    /**
3762
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3763
     */
3764
    public function __clone()
22✔
3765
    {
3766
        foreach (get_object_vars($this) as $key => $val) {
22✔
3767
            if ($key == 'parent') {
22✔
3768
                continue;
22✔
3769
            }
3770

3771
            if (is_object($val) || (is_array($val))) {
22✔
3772
                if ($key === 'cellCollection') {
22✔
3773
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
22✔
3774
                    $this->cellCollection = $newCollection;
22✔
3775
                } elseif ($key === 'drawingCollection') {
22✔
3776
                    $currentCollection = $this->drawingCollection;
22✔
3777
                    $this->drawingCollection = new ArrayObject();
22✔
3778
                    foreach ($currentCollection as $item) {
22✔
3779
                        $newDrawing = clone $item;
4✔
3780
                        $newDrawing->setWorksheet($this);
4✔
3781
                    }
3782
                } elseif ($key === 'inCellDrawingCollection') {
22✔
3783
                    $currentCollection = $this->inCellDrawingCollection;
22✔
3784
                    $this->inCellDrawingCollection = new ArrayObject();
22✔
3785
                    foreach ($currentCollection as $item) {
22✔
3786
                        $newDrawing = clone $item;
1✔
3787
                        $newDrawing->setWorksheet($this);
1✔
3788
                    }
3789
                } elseif ($key === 'tableCollection') {
22✔
3790
                    $currentCollection = $this->tableCollection;
22✔
3791
                    $this->tableCollection = new ArrayObject();
22✔
3792
                    foreach ($currentCollection as $item) {
22✔
3793
                        $newTable = clone $item;
1✔
3794
                        $newTable->setName($item->getName() . 'clone');
1✔
3795
                        $this->addTable($newTable);
1✔
3796
                    }
3797
                } elseif ($key === 'chartCollection') {
22✔
3798
                    $currentCollection = $this->chartCollection;
22✔
3799
                    $this->chartCollection = new ArrayObject();
22✔
3800
                    foreach ($currentCollection as $item) {
22✔
3801
                        $newChart = clone $item;
5✔
3802
                        $this->addChart($newChart);
5✔
3803
                    }
3804
                } elseif ($key === 'autoFilter') {
22✔
3805
                    $newAutoFilter = clone $this->autoFilter;
22✔
3806
                    $this->autoFilter = $newAutoFilter;
22✔
3807
                    $this->autoFilter->setParent($this);
22✔
3808
                } else {
3809
                    $this->{$key} = unserialize(serialize($val));
22✔
3810
                }
3811
            }
3812
        }
3813
    }
3814

3815
    /**
3816
     * Define the code name of the sheet.
3817
     *
3818
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3819
     *                       silently space to underscore)
3820
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3821
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3822
     *
3823
     * @return $this
3824
     */
3825
    public function setCodeName(string $codeName, bool $validate = true): static
11,194✔
3826
    {
3827
        // Is this a 'rename' or not?
3828
        if ($this->getCodeName() == $codeName) {
11,194✔
UNCOV
3829
            return $this;
×
3830
        }
3831

3832
        if ($validate) {
11,194✔
3833
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
11,194✔
3834

3835
            // Syntax check
3836
            // throw an exception if not valid
3837
            self::checkSheetCodeName($codeName);
11,194✔
3838

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

3841
            if ($this->parent !== null) {
11,194✔
3842
                // Is there already such sheet name?
3843
                if ($this->parent->sheetCodeNameExists($codeName)) {
11,153✔
3844
                    // Use name, but append with lowest possible integer
3845

3846
                    if (StringHelper::countCharacters($codeName) > 29) {
706✔
UNCOV
3847
                        $codeName = StringHelper::substring($codeName, 0, 29);
×
3848
                    }
3849
                    $i = 1;
706✔
3850
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
706✔
3851
                        ++$i;
285✔
3852
                        if ($i == 10) {
285✔
3853
                            if (StringHelper::countCharacters($codeName) > 28) {
2✔
UNCOV
3854
                                $codeName = StringHelper::substring($codeName, 0, 28);
×
3855
                            }
3856
                        } elseif ($i == 100) {
285✔
UNCOV
3857
                            if (StringHelper::countCharacters($codeName) > 27) {
×
UNCOV
3858
                                $codeName = StringHelper::substring($codeName, 0, 27);
×
3859
                            }
3860
                        }
3861
                    }
3862

3863
                    $codeName .= '_' . $i; // ok, we have a valid name
706✔
3864
                }
3865
            }
3866
        }
3867

3868
        $this->codeName = $codeName;
11,194✔
3869

3870
        return $this;
11,194✔
3871
    }
3872

3873
    /**
3874
     * Return the code name of the sheet.
3875
     */
3876
    public function getCodeName(): ?string
11,194✔
3877
    {
3878
        return $this->codeName;
11,194✔
3879
    }
3880

3881
    /**
3882
     * Sheet has a code name ?
3883
     */
3884
    public function hasCodeName(): bool
2✔
3885
    {
3886
        return $this->codeName !== null;
2✔
3887
    }
3888

3889
    public static function nameRequiresQuotes(string $sheetName): bool
4✔
3890
    {
3891
        return !Preg::isMatch(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName);
4✔
3892
    }
3893

3894
    public function isRowVisible(int $row): bool
125✔
3895
    {
3896
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
125✔
3897
    }
3898

3899
    /**
3900
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3901
     */
3902
    public function isCellLocked(string $coordinate): bool
1✔
3903
    {
3904
        if ($this->getProtection()->getsheet() !== true) {
1✔
3905
            return false;
1✔
3906
        }
3907
        if ($this->cellExists($coordinate)) {
1✔
3908
            return $this->getCell($coordinate)->isLocked();
1✔
3909
        }
3910
        $spreadsheet = $this->parent;
1✔
3911
        $xfIndex = $this->getXfIndex($coordinate);
1✔
3912
        if ($spreadsheet === null || $xfIndex === null) {
1✔
3913
            return true;
1✔
3914
        }
3915

UNCOV
3916
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
×
3917
    }
3918

3919
    /**
3920
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3921
     */
3922
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
1✔
3923
    {
3924
        if ($this->cellExists($coordinate)) {
1✔
3925
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
1✔
3926
        }
3927

3928
        // cell doesn't exist, therefore isn't a formula,
3929
        // therefore isn't hidden on formula bar.
3930
        return false;
1✔
3931
    }
3932

3933
    private function getXfIndex(string $coordinate): ?int
1✔
3934
    {
3935
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
1✔
3936
        $row = (int) $row;
1✔
3937
        $xfIndex = null;
1✔
3938
        if ($this->rowDimensionExists($row)) {
1✔
UNCOV
3939
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
×
3940
        }
3941
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
1✔
UNCOV
3942
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
×
3943
        }
3944

3945
        return $xfIndex;
1✔
3946
    }
3947

3948
    private string $backgroundImage = '';
3949

3950
    private string $backgroundMime = '';
3951

3952
    private string $backgroundExtension = '';
3953

3954
    public function getBackgroundImage(): string
1,064✔
3955
    {
3956
        return $this->backgroundImage;
1,064✔
3957
    }
3958

3959
    public function getBackgroundMime(): string
437✔
3960
    {
3961
        return $this->backgroundMime;
437✔
3962
    }
3963

3964
    public function getBackgroundExtension(): string
437✔
3965
    {
3966
        return $this->backgroundExtension;
437✔
3967
    }
3968

3969
    /**
3970
     * Set background image.
3971
     * Used on read/write for Xlsx.
3972
     * Used on write for Html.
3973
     *
3974
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3975
     */
3976
    public function setBackgroundImage(string $backgroundImage): self
4✔
3977
    {
3978
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
4✔
3979
        $mime = $imageArray['mime'];
4✔
3980
        if ($mime !== '') {
4✔
3981
            $extension = explode('/', $mime);
3✔
3982
            $extension = $extension[1];
3✔
3983
            $this->backgroundImage = $backgroundImage;
3✔
3984
            $this->backgroundMime = $mime;
3✔
3985
            $this->backgroundExtension = $extension;
3✔
3986
        }
3987

3988
        return $this;
4✔
3989
    }
3990

3991
    /**
3992
     * Copy cells, adjusting relative cell references in formulas.
3993
     * Acts similarly to Excel "fill handle" feature.
3994
     *
3995
     * @param string $fromCell Single source cell, e.g. C3
3996
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3997
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3998
     */
3999
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
1✔
4000
    {
4001
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
1✔
4002
        $valueString = $this->getCell($fromCell)->getValueString();
1✔
4003
        /** @var mixed[][] */
4004
        $style = $this->getStyle($fromCell)->exportArray();
1✔
4005
        $fromIndexes = Coordinate::indexesFromString($fromCell);
1✔
4006
        $referenceHelper = ReferenceHelper::getInstance();
1✔
4007
        foreach ($toArray as $destination) {
1✔
4008
            if ($destination !== $fromCell) {
1✔
4009
                $toIndexes = Coordinate::indexesFromString($destination);
1✔
4010
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
1✔
4011
                if ($copyStyle) {
1✔
4012
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
1✔
4013
                }
4014
            }
4015
        }
4016
    }
4017

4018
    public function calculateArrays(bool $preCalculateFormulas = true): void
1,231✔
4019
    {
4020
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
1,231✔
4021
            $keys = $this->cellCollection->getCoordinates();
52✔
4022
            foreach ($keys as $key) {
52✔
4023
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
52✔
4024
                    if (!Preg::isMatch(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValueString())) {
48✔
4025
                        $this->getCell($key)->getCalculatedValue();
47✔
4026
                    }
4027
                }
4028
            }
4029
        }
4030
    }
4031

4032
    public function isCellInSpillRange(string $coordinate): bool
2✔
4033
    {
4034
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
2✔
4035
            return false;
1✔
4036
        }
4037
        $this->calculateArrays();
1✔
4038
        $keys = $this->cellCollection->getCoordinates();
1✔
4039
        foreach ($keys as $key) {
1✔
4040
            $attributes = $this->getCell($key)->getFormulaAttributes();
1✔
4041
            if (isset($attributes['ref'])) {
1✔
4042
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
1✔
4043
                    // false for first cell in range, true otherwise
4044
                    return $coordinate !== $key;
1✔
4045
                }
4046
            }
4047
        }
4048

4049
        return false;
1✔
4050
    }
4051

4052
    /** @param mixed[][] $styleArray */
4053
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
2✔
4054
    {
4055
        $spreadsheet = $this->parent;
2✔
4056
        if ($spreadsheet === null) {
2✔
4057
            return false;
1✔
4058
        }
4059
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
1✔
4060
        $originalSelected = $this->selectedCells;
1✔
4061
        $this->getStyle($coordinate)->applyFromArray($styleArray);
1✔
4062
        $this->setSelectedCells($originalSelected);
1✔
4063
        if ($activeSheetIndex >= 0) {
1✔
4064
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
1✔
4065
        }
4066

4067
        return true;
1✔
4068
    }
4069

4070
    public function copyFormula(string $fromCell, string $toCell): void
1✔
4071
    {
4072
        $formula = $this->getCell($fromCell)->getValue();
1✔
4073
        $newFormula = $formula;
1✔
4074
        if (is_string($formula) && $this->getCell($fromCell)->getDataType() === DataType::TYPE_FORMULA) {
1✔
4075
            [$fromColInt, $fromRow] = Coordinate::indexesFromString($fromCell);
1✔
4076
            [$toColInt, $toRow] = Coordinate::indexesFromString($toCell);
1✔
4077
            $helper = ReferenceHelper::getInstance();
1✔
4078
            $newFormula = $helper->updateFormulaReferences(
1✔
4079
                $formula,
1✔
4080
                'A1',
1✔
4081
                $toColInt - $fromColInt,
1✔
4082
                $toRow - $fromRow
1✔
4083
            );
1✔
4084
        }
4085
        $this->setCellValue($toCell, $newFormula);
1✔
4086
    }
4087
}
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