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

PHPOffice / PhpSpreadsheet / 20582492645

29 Dec 2025 08:54PM UTC coverage: 96.123% (+0.02%) from 96.105%
20582492645

Pull #4763

github

web-flow
Merge d502dc543 into 1a01a22d2
Pull Request #4763: Merge Cell Basic, Table, and Conditional Styles

89 of 89 new or added lines in 3 files covered. (100.0%)

55 existing lines in 2 files now uncovered.

45891 of 47742 relevant lines covered (96.12%)

385.76 hits per line

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

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

3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

210
    private string $paneTopLeftCell = '';
211

212
    private string $activePane = '';
213

214
    private int $xSplit = 0;
215

216
    private int $ySplit = 0;
217

218
    private string $paneState = '';
219

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

422
        return $sheetCodeName;
11,137✔
423
    }
424

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

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

444
        return $sheetTitle;
11,137✔
445
    }
446

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

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

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

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

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

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

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

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

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

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

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

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

537
        return $chart;
106✔
538
    }
539

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

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

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

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

585
        return $chartNames;
5✔
586
    }
587

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

603
        return false;
1✔
604
    }
605

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

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

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

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

630
        return $this;
25✔
631
    }
632

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

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

647
        return $this;
9✔
648
    }
649

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

784
        return $this;
812✔
785
    }
786

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

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

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

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

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

826
        return $this;
54✔
827
    }
828

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

833
        return $this;
6✔
834
    }
835

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

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

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

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

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

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

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

899
        // Set title
900
        $this->title = $title;
11,137✔
901

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

912
        return $this;
11,137✔
913
    }
914

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

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

936
        return $this;
11,137✔
937
    }
938

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

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

956
        return $this;
1✔
957
    }
958

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

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

976
        return $this;
1✔
977
    }
978

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

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

996
        return $this;
1✔
997
    }
998

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

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

1016
        return $this;
1✔
1017
    }
1018

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

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

1036
        return $this;
1✔
1037
    }
1038

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

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

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

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

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

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

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

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

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

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

1149
        return $this;
114✔
1150
    }
1151

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1250
        return null;
×
1251
    }
1252

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1441
        return $retVal;
4✔
1442
    }
1443

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

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

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

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

1496
        return $outArray;
604✔
1497
    }
1498

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

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

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

1529
        return null;
10✔
1530
    }
1531

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

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

1557
        return $this;
55✔
1558
    }
1559

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

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

1582
        return $this;
345✔
1583
    }
1584

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

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

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

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

1625
        return $this;
2✔
1626
    }
1627

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

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

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

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

1663
        return $this;
18✔
1664
    }
1665

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

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

1687
        return $this;
33✔
1688
    }
1689

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

1711
        return $breaks;
685✔
1712
    }
1713

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

1725
        return $this->rowBreaks;
569✔
1726
    }
1727

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

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

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

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

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

1755
        return $this->columnBreaks;
568✔
1756
    }
1757

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

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

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

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

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

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

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

1813
        return $this;
167✔
1814
    }
1815

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

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

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

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

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

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

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

1881
        return $leftCellValue;
58✔
1882
    }
1883

1884
    /**
1885
     * Remove merge on a cell range.
1886
     *
1887
     * @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'
1888
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1889
     *              or an AddressRange.
1890
     *
1891
     * @return $this
1892
     */
1893
    public function unmergeCells(AddressRange|string|array $range): static
23✔
1894
    {
1895
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
23✔
1896

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

1907
        return $this;
22✔
1908
    }
1909

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

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

1932
        return $this;
126✔
1933
    }
1934

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

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

1955
        return $this;
28✔
1956
    }
1957

1958
    /**
1959
     * Remove protection on a cell or cell range.
1960
     *
1961
     * @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'
1962
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1963
     *              or a CellAddress or AddressRange object.
1964
     *
1965
     * @return $this
1966
     */
1967
    public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static
22✔
1968
    {
1969
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
22✔
1970

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

1977
        return $this;
21✔
1978
    }
1979

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

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

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

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

2018
        return $this;
20✔
2019
    }
2020

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

2028
        return $this;
1✔
2029
    }
2030

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

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

2051
        return $this;
103✔
2052
    }
2053

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

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

2066
        return $tableNames;
1✔
2067
    }
2068

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

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

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

2096
        return null;
41✔
2097
    }
2098

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

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

2114
        return $this;
1✔
2115
    }
2116

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

2124
        return $this;
1✔
2125
    }
2126

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

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

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

2176
        $topLeftCell = "$topLeftCell";
49✔
2177
        $this->paneTopLeftCell = $topLeftCell;
49✔
2178

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

2199
        return $this;
49✔
2200
    }
2201

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

2206
        return $this;
59✔
2207
    }
2208

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

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

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

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

2236
        return $this;
26✔
2237
    }
2238

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

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

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

2255
        return $this;
46✔
2256
    }
2257

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

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

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

2273
        return $this;
49✔
2274
    }
2275

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

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

2288
        return $this;
11✔
2289
    }
2290

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

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

2303
        return $this;
26✔
2304
    }
2305

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

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

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

2326
        return $this;
26✔
2327
    }
2328

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

2346
        return $this;
42✔
2347
    }
2348

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

2366
        return $this;
49✔
2367
    }
2368

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

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

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

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

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

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

2454
        $this->rowDimensions = $holdRowDimensions;
52✔
2455

2456
        return $this;
52✔
2457
    }
2458

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

2476
        return $holdRowDimensions;
52✔
2477
    }
2478

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

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

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

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

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

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

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

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

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

2555
        return $this;
33✔
2556
    }
2557

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

2576
        return $holdColumnDimensions;
42✔
2577
    }
2578

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

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

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

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

2615
        return $this;
892✔
2616
    }
2617

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

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

2637
        return $this;
588✔
2638
    }
2639

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

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

2659
        return $this;
424✔
2660
    }
2661

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

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

2681
        return $this;
423✔
2682
    }
2683

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

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

2703
        return $this;
423✔
2704
    }
2705

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

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

2727
        return $this;
126✔
2728
    }
2729

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

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

2754
        return $this;
55✔
2755
    }
2756

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

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

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

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

2786
        return $newComment;
116✔
2787
    }
2788

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

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

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

2819
    /**
2820
     * Select a range of cells.
2821
     *
2822
     * @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'
2823
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2824
     *              or a CellAddress or AddressRange object.
2825
     *
2826
     * @return $this
2827
     */
2828
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
10,702✔
2829
    {
2830
        if (is_string($coordinate)) {
10,702✔
2831
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
10,702✔
2832
        }
2833
        $coordinate = Validations::validateCellOrCellRange($coordinate);
10,702✔
2834

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

2844
        return $this;
10,702✔
2845
    }
2846

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

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

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

2885
        return $this;
162✔
2886
    }
2887

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

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

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

2936
        return $this;
858✔
2937
    }
2938

2939
    /**
2940
     * @param bool $calculateFormulas Whether to calculate cell's value if it is a formula.
2941
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2942
     * @param bool $formatData Whether to format data according to cell's style.
2943
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
2944
     *
2945
     * @throws Exception
2946
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2947
     */
2948
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue, bool $lessFloatPrecision = false): mixed
186✔
2949
    {
2950
        $returnValue = $nullValue;
186✔
2951

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

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

2971
        return $returnValue;
186✔
2972
    }
2973

2974
    /**
2975
     * Create array from a range of cells.
2976
     *
2977
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2978
     * @param bool $calculateFormulas Should formulas be calculated?
2979
     * @param bool $formatData Should formatting be applied to cell values?
2980
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2981
     *                             True - Return rows and columns indexed by their actual row and column IDs
2982
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2983
     *                            True - Don't return values for rows/columns that are defined as hidden.
2984
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
2985
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
2986
     *
2987
     * @return mixed[][]
2988
     */
2989
    public function rangeToArray(
154✔
2990
        string $range,
2991
        mixed $nullValue = null,
2992
        bool $calculateFormulas = true,
2993
        bool $formatData = true,
2994
        bool $returnCellRef = false,
2995
        bool $ignoreHidden = false,
2996
        bool $reduceArrays = false,
2997
        bool $lessFloatPrecision = false
2998
    ): array {
2999
        $returnValue = [];
154✔
3000

3001
        // Loop through rows
3002
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision) as $rowRef => $rowArray) {
154✔
3003
            /** @var int $rowRef */
3004
            $returnValue[$rowRef] = $rowArray;
154✔
3005
        }
3006

3007
        // Return
3008
        return $returnValue;
154✔
3009
    }
3010

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

3038
        $parts = explode(',', $ranges);
3✔
3039
        foreach ($parts as $part) {
3✔
3040
            // Loop through rows
3041
            foreach ($this->rangeToArrayYieldRows($part, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision) as $rowRef => $rowArray) {
3✔
3042
                /** @var int $rowRef */
3043
                $returnValue[$rowRef] = $rowArray;
3✔
3044
            }
3045
        }
3046

3047
        // Return
3048
        return $returnValue;
3✔
3049
    }
3050

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

3078
        //    Identify the range that we need to extract from the worksheet
3079
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
186✔
3080
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
186✔
3081
        $minRow = $rangeStart[1];
186✔
3082
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
186✔
3083
        $maxRow = $rangeEnd[1];
186✔
3084
        $minColInt = $rangeStart[0];
186✔
3085
        $maxColInt = $rangeEnd[0];
186✔
3086

3087
        StringHelper::stringIncrement($maxCol);
186✔
3088
        /** @var array<string, bool> */
3089
        $hiddenColumns = [];
186✔
3090
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
186✔
3091
        $hideColumns = !empty($hiddenColumns);
186✔
3092

3093
        $keys = $this->cellCollection->getSortedCoordinatesInt();
186✔
3094
        $keyIndex = 0;
186✔
3095
        $keysCount = count($keys);
186✔
3096
        // Loop through rows
3097
        for ($row = $minRow; $row <= $maxRow; ++$row) {
186✔
3098
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
186✔
3099
                continue;
4✔
3100
            }
3101
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
186✔
3102
            $returnValue = $nullRow;
186✔
3103

3104
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
186✔
3105
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
186✔
3106

3107
            // Binary search to quickly approach the correct index
3108
            $keyIndex = intdiv($keysCount, 2);
186✔
3109
            $boundLow = 0;
186✔
3110
            $boundHigh = $keysCount - 1;
186✔
3111
            while ($boundLow <= $boundHigh) {
186✔
3112
                $keyIndex = intdiv($boundLow + $boundHigh, 2);
186✔
3113
                if ($keys[$keyIndex] < $index) {
186✔
3114
                    $boundLow = $keyIndex + 1;
154✔
3115
                } elseif ($keys[$keyIndex] > $index) {
186✔
3116
                    $boundHigh = $keyIndex - 1;
168✔
3117
                } else {
3118
                    break;
178✔
3119
                }
3120
            }
3121

3122
            // Realign to the proper index value
3123
            while ($keyIndex > 0 && $keys[$keyIndex] > $index) {
186✔
3124
                --$keyIndex;
14✔
3125
            }
3126
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
186✔
3127
                ++$keyIndex;
20✔
3128
            }
3129

3130
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
186✔
3131
                $key = $keys[$keyIndex];
186✔
3132
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
186✔
3133
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
186✔
3134
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
186✔
3135
                    $col = Coordinate::stringFromColumnIndex($thisCol);
186✔
3136
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
186✔
3137
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
186✔
3138
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
186✔
3139
                        if ($cell !== null) {
186✔
3140
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue, lessFloatPrecision: $lessFloatPrecision);
186✔
3141
                            if ($reduceArrays) {
186✔
3142
                                while (is_array($value)) {
21✔
3143
                                    $value = array_shift($value);
19✔
3144
                                }
3145
                            }
3146
                            if ($value !== $nullValue) {
186✔
3147
                                $returnValue[$columnRef] = $value;
186✔
3148
                            }
3149
                        }
3150
                    }
3151
                }
3152
                ++$keyIndex;
186✔
3153
            }
3154

3155
            yield $rowRef => $returnValue;
186✔
3156
        }
3157
    }
3158

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

3192
        return $nullRow;
186✔
3193
    }
3194

3195
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
19✔
3196
    {
3197
        $namedRange = DefinedName::resolveName($definedName, $this);
19✔
3198
        if ($namedRange === null) {
19✔
3199
            if ($returnNullIfInvalid) {
6✔
3200
                return null;
5✔
3201
            }
3202

3203
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
1✔
3204
        }
3205

3206
        if ($namedRange->isFormula()) {
13✔
UNCOV
3207
            if ($returnNullIfInvalid) {
×
UNCOV
3208
                return null;
×
3209
            }
3210

UNCOV
3211
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
×
3212
        }
3213

3214
        if ($namedRange->getLocalOnly()) {
13✔
3215
            $worksheet = $namedRange->getWorksheet();
2✔
3216
            if ($worksheet === null || $this !== $worksheet) {
2✔
UNCOV
3217
                if ($returnNullIfInvalid) {
×
UNCOV
3218
                    return null;
×
3219
                }
3220

UNCOV
3221
                throw new Exception(
×
UNCOV
3222
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
×
UNCOV
3223
                );
×
3224
            }
3225
        }
3226

3227
        return $namedRange;
13✔
3228
    }
3229

3230
    /**
3231
     * Create array from a range of cells.
3232
     *
3233
     * @param string $definedName The Named Range that should be returned
3234
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3235
     * @param bool $calculateFormulas Should formulas be calculated?
3236
     * @param bool $formatData Should formatting be applied to cell values?
3237
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3238
     *                             True - Return rows and columns indexed by their actual row and column IDs
3239
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3240
     *                            True - Don't return values for rows/columns that are defined as hidden.
3241
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3242
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3243
     *
3244
     * @return mixed[][]
3245
     */
3246
    public function namedRangeToArray(
2✔
3247
        string $definedName,
3248
        mixed $nullValue = null,
3249
        bool $calculateFormulas = true,
3250
        bool $formatData = true,
3251
        bool $returnCellRef = false,
3252
        bool $ignoreHidden = false,
3253
        bool $reduceArrays = false,
3254
        bool $lessFloatPrecision = false
3255
    ): array {
3256
        $retVal = [];
2✔
3257
        $namedRange = $this->validateNamedRange($definedName);
2✔
3258
        if ($namedRange !== null) {
1✔
3259
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
1✔
3260
            $cellRange = str_replace('$', '', $cellRange);
1✔
3261
            $workSheet = $namedRange->getWorksheet();
1✔
3262
            if ($workSheet !== null) {
1✔
3263
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision);
1✔
3264
            }
3265
        }
3266

3267
        return $retVal;
1✔
3268
    }
3269

3270
    /**
3271
     * Create array from worksheet.
3272
     *
3273
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3274
     * @param bool $calculateFormulas Should formulas be calculated?
3275
     * @param bool $formatData Should formatting be applied to cell values?
3276
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3277
     *                             True - Return rows and columns indexed by their actual row and column IDs
3278
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3279
     *                            True - Don't return values for rows/columns that are defined as hidden.
3280
     * @param bool $reduceArrays If true and result is a formula which evaluates to an array, reduce it to the top leftmost value.
3281
     * @param bool $lessFloatPrecision If true, formatting unstyled floats will convert them to a more human-friendly but less computationally accurate value
3282
     *
3283
     * @return mixed[][]
3284
     */
3285
    public function toArray(
85✔
3286
        mixed $nullValue = null,
3287
        bool $calculateFormulas = true,
3288
        bool $formatData = true,
3289
        bool $returnCellRef = false,
3290
        bool $ignoreHidden = false,
3291
        bool $reduceArrays = false,
3292
        bool $lessFloatPrecision = false
3293
    ): array {
3294
        // Garbage collect...
3295
        $this->garbageCollect();
85✔
3296
        $this->calculateArrays($calculateFormulas);
85✔
3297

3298
        //    Identify the range that we need to extract from the worksheet
3299
        $maxCol = $this->getHighestColumn();
85✔
3300
        $maxRow = $this->getHighestRow();
85✔
3301

3302
        // Return
3303
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays, $lessFloatPrecision);
85✔
3304
    }
3305

3306
    /**
3307
     * Get row iterator.
3308
     *
3309
     * @param int $startRow The row number at which to start iterating
3310
     * @param ?int $endRow The row number at which to stop iterating
3311
     */
3312
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
97✔
3313
    {
3314
        return new RowIterator($this, $startRow, $endRow);
97✔
3315
    }
3316

3317
    /**
3318
     * Get column iterator.
3319
     *
3320
     * @param string $startColumn The column address at which to start iterating
3321
     * @param ?string $endColumn The column address at which to stop iterating
3322
     */
3323
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
26✔
3324
    {
3325
        return new ColumnIterator($this, $startColumn, $endColumn);
26✔
3326
    }
3327

3328
    /**
3329
     * Run PhpSpreadsheet garbage collector.
3330
     *
3331
     * @return $this
3332
     */
3333
    public function garbageCollect(): static
1,238✔
3334
    {
3335
        // Flush cache
3336
        $this->cellCollection->get('A1');
1,238✔
3337

3338
        // Lookup highest column and highest row if cells are cleaned
3339
        $colRow = $this->cellCollection->getHighestRowAndColumn();
1,238✔
3340
        $highestRow = $colRow['row'];
1,238✔
3341
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
1,238✔
3342

3343
        // Loop through column dimensions
3344
        foreach ($this->columnDimensions as $dimension) {
1,238✔
3345
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
174✔
3346
        }
3347

3348
        // Loop through row dimensions
3349
        foreach ($this->rowDimensions as $dimension) {
1,238✔
3350
            $highestRow = max($highestRow, $dimension->getRowIndex());
116✔
3351
        }
3352

3353
        // Cache values
3354
        $this->cachedHighestColumn = max(1, $highestColumn);
1,238✔
3355
        /** @var int $highestRow */
3356
        $this->cachedHighestRow = $highestRow;
1,238✔
3357

3358
        // Return
3359
        return $this;
1,238✔
3360
    }
3361

3362
    /**
3363
     * @deprecated 5.2.0 Serves no useful purpose. No replacement.
3364
     *
3365
     * @codeCoverageIgnore
3366
     */
3367
    public function getHashInt(): int
3368
    {
3369
        return spl_object_id($this);
3370
    }
3371

3372
    /**
3373
     * Extract worksheet title from range.
3374
     *
3375
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3376
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3377
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3378
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3379
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3380
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3381
     *
3382
     * @param ?string $range Range to extract title from
3383
     * @param bool $returnRange Return range? (see example)
3384
     *
3385
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3386
     */
3387
    public static function extractSheetTitle(?string $range, bool $returnRange = false, bool $unapostrophize = false): array|null|string
10,930✔
3388
    {
3389
        if (empty($range)) {
10,930✔
3390
            return $returnRange ? [null, null] : null;
13✔
3391
        }
3392

3393
        // Sheet title included?
3394
        if (($sep = strrpos($range, '!')) === false) {
10,928✔
3395
            return $returnRange ? ['', $range] : '';
10,899✔
3396
        }
3397

3398
        if ($returnRange) {
1,450✔
3399
            $title = substr($range, 0, $sep);
1,450✔
3400
            if ($unapostrophize) {
1,450✔
3401
                $title = self::unApostrophizeTitle($title);
1,390✔
3402
            }
3403

3404
            return [$title, substr($range, $sep + 1)];
1,450✔
3405
        }
3406

3407
        return substr($range, $sep + 1);
7✔
3408
    }
3409

3410
    public static function unApostrophizeTitle(?string $title): string
1,404✔
3411
    {
3412
        $title ??= '';
1,404✔
3413
        if (str_starts_with($title, "'") && str_ends_with($title, "'")) {
1,404✔
3414
            $title = str_replace("''", "'", substr($title, 1, -1));
1,329✔
3415
        }
3416

3417
        return $title;
1,404✔
3418
    }
3419

3420
    /**
3421
     * Get hyperlink.
3422
     *
3423
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3424
     */
3425
    public function getHyperlink(string $cellCoordinate): Hyperlink
99✔
3426
    {
3427
        // return hyperlink if we already have one
3428
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
99✔
3429
            return $this->hyperlinkCollection[$cellCoordinate];
45✔
3430
        }
3431

3432
        // else create hyperlink
3433
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
99✔
3434

3435
        return $this->hyperlinkCollection[$cellCoordinate];
99✔
3436
    }
3437

3438
    /**
3439
     * Set hyperlink.
3440
     *
3441
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3442
     *
3443
     * @return $this
3444
     */
3445
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static
55✔
3446
    {
3447
        if ($hyperlink === null) {
55✔
3448
            unset($this->hyperlinkCollection[$cellCoordinate]);
54✔
3449
        } else {
3450
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
21✔
3451
        }
3452

3453
        return $this;
55✔
3454
    }
3455

3456
    /**
3457
     * Hyperlink at a specific coordinate exists?
3458
     *
3459
     * @param string $coordinate eg: 'A1'
3460
     */
3461
    public function hyperlinkExists(string $coordinate): bool
560✔
3462
    {
3463
        return isset($this->hyperlinkCollection[$coordinate]);
560✔
3464
    }
3465

3466
    /**
3467
     * Get collection of hyperlinks.
3468
     *
3469
     * @return Hyperlink[]
3470
     */
3471
    public function getHyperlinkCollection(): array
673✔
3472
    {
3473
        return $this->hyperlinkCollection;
673✔
3474
    }
3475

3476
    /**
3477
     * Get data validation.
3478
     *
3479
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3480
     */
3481
    public function getDataValidation(string $cellCoordinate): DataValidation
37✔
3482
    {
3483
        // return data validation if we already have one
3484
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
37✔
3485
            return $this->dataValidationCollection[$cellCoordinate];
28✔
3486
        }
3487

3488
        // or if cell is part of a data validation range
3489
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
28✔
3490
            $keyParts = explode(' ', $key);
12✔
3491
            foreach ($keyParts as $keyPart) {
12✔
3492
                if ($keyPart === $cellCoordinate) {
12✔
3493
                    return $dataValidation;
1✔
3494
                }
3495
                if (str_contains($keyPart, ':')) {
12✔
3496
                    if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) {
9✔
3497
                        return $dataValidation;
9✔
3498
                    }
3499
                }
3500
            }
3501
        }
3502

3503
        // else create data validation
3504
        $dataValidation = new DataValidation();
20✔
3505
        $dataValidation->setSqref($cellCoordinate);
20✔
3506
        $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
20✔
3507

3508
        return $dataValidation;
20✔
3509
    }
3510

3511
    /**
3512
     * Set data validation.
3513
     *
3514
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3515
     *
3516
     * @return $this
3517
     */
3518
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
92✔
3519
    {
3520
        if ($dataValidation === null) {
92✔
3521
            unset($this->dataValidationCollection[$cellCoordinate]);
59✔
3522
        } else {
3523
            $dataValidation->setSqref($cellCoordinate);
40✔
3524
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
40✔
3525
        }
3526

3527
        return $this;
92✔
3528
    }
3529

3530
    /**
3531
     * Data validation at a specific coordinate exists?
3532
     *
3533
     * @param string $coordinate eg: 'A1'
3534
     */
3535
    public function dataValidationExists(string $coordinate): bool
25✔
3536
    {
3537
        if (isset($this->dataValidationCollection[$coordinate])) {
25✔
3538
            return true;
23✔
3539
        }
3540
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
8✔
3541
            $keyParts = explode(' ', $key);
7✔
3542
            foreach ($keyParts as $keyPart) {
7✔
3543
                if ($keyPart === $coordinate) {
7✔
3544
                    return true;
1✔
3545
                }
3546
                if (str_contains($keyPart, ':')) {
7✔
3547
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
2✔
3548
                        return true;
2✔
3549
                    }
3550
                }
3551
            }
3552
        }
3553

3554
        return false;
6✔
3555
    }
3556

3557
    /**
3558
     * Get collection of data validations.
3559
     *
3560
     * @return DataValidation[]
3561
     */
3562
    public function getDataValidationCollection(): array
674✔
3563
    {
3564
        $collectionCells = [];
674✔
3565
        $collectionRanges = [];
674✔
3566
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
674✔
3567
            if (Preg::isMatch('/[: ]/', $key)) {
27✔
3568
                $collectionRanges[$key] = $dataValidation;
15✔
3569
            } else {
3570
                $collectionCells[$key] = $dataValidation;
22✔
3571
            }
3572
        }
3573

3574
        return array_merge($collectionCells, $collectionRanges);
674✔
3575
    }
3576

3577
    /**
3578
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3579
     *
3580
     * @return string Adjusted range value
3581
     */
UNCOV
3582
    public function shrinkRangeToFit(string $range): string
×
3583
    {
UNCOV
3584
        $maxCol = $this->getHighestColumn();
×
UNCOV
3585
        $maxRow = $this->getHighestRow();
×
UNCOV
3586
        $maxCol = Coordinate::columnIndexFromString($maxCol);
×
3587

UNCOV
3588
        $rangeBlocks = explode(' ', $range);
×
UNCOV
3589
        foreach ($rangeBlocks as &$rangeSet) {
×
UNCOV
3590
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
×
3591

UNCOV
3592
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
×
UNCOV
3593
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3594
            }
UNCOV
3595
            if ($rangeBoundaries[0][1] > $maxRow) {
×
UNCOV
3596
                $rangeBoundaries[0][1] = $maxRow;
×
3597
            }
UNCOV
3598
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
×
UNCOV
3599
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
×
3600
            }
UNCOV
3601
            if ($rangeBoundaries[1][1] > $maxRow) {
×
UNCOV
3602
                $rangeBoundaries[1][1] = $maxRow;
×
3603
            }
UNCOV
3604
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
×
3605
        }
UNCOV
3606
        unset($rangeSet);
×
3607

UNCOV
3608
        return implode(' ', $rangeBlocks);
×
3609
    }
3610

3611
    /**
3612
     * Get tab color.
3613
     */
3614
    public function getTabColor(): Color
23✔
3615
    {
3616
        if ($this->tabColor === null) {
23✔
3617
            $this->tabColor = new Color();
23✔
3618
        }
3619

3620
        return $this->tabColor;
23✔
3621
    }
3622

3623
    /**
3624
     * Reset tab color.
3625
     *
3626
     * @return $this
3627
     */
3628
    public function resetTabColor(): static
1✔
3629
    {
3630
        $this->tabColor = null;
1✔
3631

3632
        return $this;
1✔
3633
    }
3634

3635
    /**
3636
     * Tab color set?
3637
     */
3638
    public function isTabColorSet(): bool
567✔
3639
    {
3640
        return $this->tabColor !== null;
567✔
3641
    }
3642

3643
    /**
3644
     * Copy worksheet (!= clone!).
3645
     */
UNCOV
3646
    public function copy(): static
×
3647
    {
UNCOV
3648
        return clone $this;
×
3649
    }
3650

3651
    /**
3652
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3653
     *          exist in the collection for this row. false will be returned otherwise.
3654
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3655
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3656
     *                  cells, then the row will be considered empty.
3657
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3658
     *                  string value cells, then the row will be considered empty.
3659
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3660
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3661
     *                  will be considered empty.
3662
     *
3663
     * @param int $definitionOfEmptyFlags
3664
     *              Possible Flag Values are:
3665
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3666
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3667
     */
3668
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
9✔
3669
    {
3670
        try {
3671
            $iterator = new RowIterator($this, $rowId, $rowId);
9✔
3672
            $iterator->seek($rowId);
8✔
3673
            $row = $iterator->current();
8✔
3674
        } catch (Exception) {
1✔
3675
            return true;
1✔
3676
        }
3677

3678
        return $row->isEmpty($definitionOfEmptyFlags);
8✔
3679
    }
3680

3681
    /**
3682
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3683
     *          exist in the collection for this column. false will be returned otherwise.
3684
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3685
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3686
     *                  cells, then the column will be considered empty.
3687
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3688
     *                  string value cells, then the column will be considered empty.
3689
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3690
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3691
     *                  will be considered empty.
3692
     *
3693
     * @param int $definitionOfEmptyFlags
3694
     *              Possible Flag Values are:
3695
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3696
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3697
     */
3698
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
9✔
3699
    {
3700
        try {
3701
            $iterator = new ColumnIterator($this, $columnId, $columnId);
9✔
3702
            $iterator->seek($columnId);
8✔
3703
            $column = $iterator->current();
8✔
3704
        } catch (Exception) {
1✔
3705
            return true;
1✔
3706
        }
3707

3708
        return $column->isEmpty($definitionOfEmptyFlags);
8✔
3709
    }
3710

3711
    /**
3712
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3713
     */
3714
    public function __clone()
21✔
3715
    {
3716
        foreach (get_object_vars($this) as $key => $val) {
21✔
3717
            if ($key == 'parent') {
21✔
3718
                continue;
21✔
3719
            }
3720

3721
            if (is_object($val) || (is_array($val))) {
21✔
3722
                if ($key === 'cellCollection') {
21✔
3723
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
21✔
3724
                    $this->cellCollection = $newCollection;
21✔
3725
                } elseif ($key === 'drawingCollection') {
21✔
3726
                    $currentCollection = $this->drawingCollection;
21✔
3727
                    $this->drawingCollection = new ArrayObject();
21✔
3728
                    foreach ($currentCollection as $item) {
21✔
3729
                        $newDrawing = clone $item;
4✔
3730
                        $newDrawing->setWorksheet($this);
4✔
3731
                    }
3732
                } elseif ($key === 'tableCollection') {
21✔
3733
                    $currentCollection = $this->tableCollection;
21✔
3734
                    $this->tableCollection = new ArrayObject();
21✔
3735
                    foreach ($currentCollection as $item) {
21✔
3736
                        $newTable = clone $item;
1✔
3737
                        $newTable->setName($item->getName() . 'clone');
1✔
3738
                        $this->addTable($newTable);
1✔
3739
                    }
3740
                } elseif ($key === 'chartCollection') {
21✔
3741
                    $currentCollection = $this->chartCollection;
21✔
3742
                    $this->chartCollection = new ArrayObject();
21✔
3743
                    foreach ($currentCollection as $item) {
21✔
3744
                        $newChart = clone $item;
5✔
3745
                        $this->addChart($newChart);
5✔
3746
                    }
3747
                } elseif ($key === 'autoFilter') {
21✔
3748
                    $newAutoFilter = clone $this->autoFilter;
21✔
3749
                    $this->autoFilter = $newAutoFilter;
21✔
3750
                    $this->autoFilter->setParent($this);
21✔
3751
                } else {
3752
                    $this->{$key} = unserialize(serialize($val));
21✔
3753
                }
3754
            }
3755
        }
3756
    }
3757

3758
    /**
3759
     * Define the code name of the sheet.
3760
     *
3761
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3762
     *                       silently space to underscore)
3763
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3764
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3765
     *
3766
     * @return $this
3767
     */
3768
    public function setCodeName(string $codeName, bool $validate = true): static
11,137✔
3769
    {
3770
        // Is this a 'rename' or not?
3771
        if ($this->getCodeName() == $codeName) {
11,137✔
UNCOV
3772
            return $this;
×
3773
        }
3774

3775
        if ($validate) {
11,137✔
3776
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
11,137✔
3777

3778
            // Syntax check
3779
            // throw an exception if not valid
3780
            self::checkSheetCodeName($codeName);
11,137✔
3781

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

3784
            if ($this->parent !== null) {
11,137✔
3785
                // Is there already such sheet name?
3786
                if ($this->parent->sheetCodeNameExists($codeName)) {
11,096✔
3787
                    // Use name, but append with lowest possible integer
3788

3789
                    if (StringHelper::countCharacters($codeName) > 29) {
699✔
UNCOV
3790
                        $codeName = StringHelper::substring($codeName, 0, 29);
×
3791
                    }
3792
                    $i = 1;
699✔
3793
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
699✔
3794
                        ++$i;
285✔
3795
                        if ($i == 10) {
285✔
3796
                            if (StringHelper::countCharacters($codeName) > 28) {
2✔
3797
                                $codeName = StringHelper::substring($codeName, 0, 28);
×
3798
                            }
3799
                        } elseif ($i == 100) {
285✔
UNCOV
3800
                            if (StringHelper::countCharacters($codeName) > 27) {
×
UNCOV
3801
                                $codeName = StringHelper::substring($codeName, 0, 27);
×
3802
                            }
3803
                        }
3804
                    }
3805

3806
                    $codeName .= '_' . $i; // ok, we have a valid name
699✔
3807
                }
3808
            }
3809
        }
3810

3811
        $this->codeName = $codeName;
11,137✔
3812

3813
        return $this;
11,137✔
3814
    }
3815

3816
    /**
3817
     * Return the code name of the sheet.
3818
     */
3819
    public function getCodeName(): ?string
11,137✔
3820
    {
3821
        return $this->codeName;
11,137✔
3822
    }
3823

3824
    /**
3825
     * Sheet has a code name ?
3826
     */
3827
    public function hasCodeName(): bool
2✔
3828
    {
3829
        return $this->codeName !== null;
2✔
3830
    }
3831

3832
    public static function nameRequiresQuotes(string $sheetName): bool
4✔
3833
    {
3834
        return !Preg::isMatch(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName);
4✔
3835
    }
3836

3837
    public function isRowVisible(int $row): bool
124✔
3838
    {
3839
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
124✔
3840
    }
3841

3842
    /**
3843
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3844
     */
3845
    public function isCellLocked(string $coordinate): bool
1✔
3846
    {
3847
        if ($this->getProtection()->getsheet() !== true) {
1✔
3848
            return false;
1✔
3849
        }
3850
        if ($this->cellExists($coordinate)) {
1✔
3851
            return $this->getCell($coordinate)->isLocked();
1✔
3852
        }
3853
        $spreadsheet = $this->parent;
1✔
3854
        $xfIndex = $this->getXfIndex($coordinate);
1✔
3855
        if ($spreadsheet === null || $xfIndex === null) {
1✔
3856
            return true;
1✔
3857
        }
3858

UNCOV
3859
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
×
3860
    }
3861

3862
    /**
3863
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3864
     */
3865
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
1✔
3866
    {
3867
        if ($this->cellExists($coordinate)) {
1✔
3868
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
1✔
3869
        }
3870

3871
        // cell doesn't exist, therefore isn't a formula,
3872
        // therefore isn't hidden on formula bar.
3873
        return false;
1✔
3874
    }
3875

3876
    private function getXfIndex(string $coordinate): ?int
1✔
3877
    {
3878
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
1✔
3879
        $row = (int) $row;
1✔
3880
        $xfIndex = null;
1✔
3881
        if ($this->rowDimensionExists($row)) {
1✔
UNCOV
3882
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
×
3883
        }
3884
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
1✔
UNCOV
3885
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
×
3886
        }
3887

3888
        return $xfIndex;
1✔
3889
    }
3890

3891
    private string $backgroundImage = '';
3892

3893
    private string $backgroundMime = '';
3894

3895
    private string $backgroundExtension = '';
3896

3897
    public function getBackgroundImage(): string
1,044✔
3898
    {
3899
        return $this->backgroundImage;
1,044✔
3900
    }
3901

3902
    public function getBackgroundMime(): string
423✔
3903
    {
3904
        return $this->backgroundMime;
423✔
3905
    }
3906

3907
    public function getBackgroundExtension(): string
423✔
3908
    {
3909
        return $this->backgroundExtension;
423✔
3910
    }
3911

3912
    /**
3913
     * Set background image.
3914
     * Used on read/write for Xlsx.
3915
     * Used on write for Html.
3916
     *
3917
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3918
     */
3919
    public function setBackgroundImage(string $backgroundImage): self
4✔
3920
    {
3921
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
4✔
3922
        $mime = $imageArray['mime'];
4✔
3923
        if ($mime !== '') {
4✔
3924
            $extension = explode('/', $mime);
3✔
3925
            $extension = $extension[1];
3✔
3926
            $this->backgroundImage = $backgroundImage;
3✔
3927
            $this->backgroundMime = $mime;
3✔
3928
            $this->backgroundExtension = $extension;
3✔
3929
        }
3930

3931
        return $this;
4✔
3932
    }
3933

3934
    /**
3935
     * Copy cells, adjusting relative cell references in formulas.
3936
     * Acts similarly to Excel "fill handle" feature.
3937
     *
3938
     * @param string $fromCell Single source cell, e.g. C3
3939
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3940
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3941
     */
3942
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
1✔
3943
    {
3944
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
1✔
3945
        $valueString = $this->getCell($fromCell)->getValueString();
1✔
3946
        /** @var mixed[][] */
3947
        $style = $this->getStyle($fromCell)->exportArray();
1✔
3948
        $fromIndexes = Coordinate::indexesFromString($fromCell);
1✔
3949
        $referenceHelper = ReferenceHelper::getInstance();
1✔
3950
        foreach ($toArray as $destination) {
1✔
3951
            if ($destination !== $fromCell) {
1✔
3952
                $toIndexes = Coordinate::indexesFromString($destination);
1✔
3953
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
1✔
3954
                if ($copyStyle) {
1✔
3955
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
1✔
3956
                }
3957
            }
3958
        }
3959
    }
3960

3961
    public function calculateArrays(bool $preCalculateFormulas = true): void
1,211✔
3962
    {
3963
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
1,211✔
3964
            $keys = $this->cellCollection->getCoordinates();
46✔
3965
            foreach ($keys as $key) {
46✔
3966
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
46✔
3967
                    if (!Preg::isMatch(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValueString())) {
46✔
3968
                        $this->getCell($key)->getCalculatedValue();
45✔
3969
                    }
3970
                }
3971
            }
3972
        }
3973
    }
3974

3975
    public function isCellInSpillRange(string $coordinate): bool
2✔
3976
    {
3977
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
2✔
3978
            return false;
1✔
3979
        }
3980
        $this->calculateArrays();
1✔
3981
        $keys = $this->cellCollection->getCoordinates();
1✔
3982
        foreach ($keys as $key) {
1✔
3983
            $attributes = $this->getCell($key)->getFormulaAttributes();
1✔
3984
            if (isset($attributes['ref'])) {
1✔
3985
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
1✔
3986
                    // false for first cell in range, true otherwise
3987
                    return $coordinate !== $key;
1✔
3988
                }
3989
            }
3990
        }
3991

3992
        return false;
1✔
3993
    }
3994

3995
    /** @param mixed[][] $styleArray */
3996
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
2✔
3997
    {
3998
        $spreadsheet = $this->parent;
2✔
3999
        if ($spreadsheet === null) {
2✔
4000
            return false;
1✔
4001
        }
4002
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
1✔
4003
        $originalSelected = $this->selectedCells;
1✔
4004
        $this->getStyle($coordinate)->applyFromArray($styleArray);
1✔
4005
        $this->setSelectedCells($originalSelected);
1✔
4006
        if ($activeSheetIndex >= 0) {
1✔
4007
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
1✔
4008
        }
4009

4010
        return true;
1✔
4011
    }
4012

4013
    public function copyFormula(string $fromCell, string $toCell): void
1✔
4014
    {
4015
        $formula = $this->getCell($fromCell)->getValue();
1✔
4016
        $newFormula = $formula;
1✔
4017
        if (is_string($formula) && $this->getCell($fromCell)->getDataType() === DataType::TYPE_FORMULA) {
1✔
4018
            [$fromColInt, $fromRow] = Coordinate::indexesFromString($fromCell);
1✔
4019
            [$toColInt, $toRow] = Coordinate::indexesFromString($toCell);
1✔
4020
            $helper = ReferenceHelper::getInstance();
1✔
4021
            $newFormula = $helper->updateFormulaReferences(
1✔
4022
                $formula,
1✔
4023
                'A1',
1✔
4024
                $toColInt - $fromColInt,
1✔
4025
                $toRow - $fromRow
1✔
4026
            );
1✔
4027
        }
4028
        $this->setCellValue($toCell, $newFormula);
1✔
4029
    }
4030
}
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