Failed Conditions
Pull Request — master (#3528)
by Owen
22:26 queued 11:58
created

ReferenceHelper::adjustHyperlinks()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.0178

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 17
rs 8.8333
ccs 13
cts 14
cp 0.9286
cc 7
nc 20
nop 3
crap 7.0178
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
7
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
8
use PhpOffice\PhpSpreadsheet\Cell\DataType;
9
use PhpOffice\PhpSpreadsheet\Style\Conditional;
10
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter;
11
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
12
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
13
14
class ReferenceHelper
15
{
16
    /**    Constants                */
17
    /**    Regular Expressions      */
18
    private const SHEETNAME_PART = '((\w*|\'[^!]*\')!)';
19
    private const SHEETNAME_PART_WITH_SLASHES = '/' . self::SHEETNAME_PART . '/';
20
    const REFHELPER_REGEXP_CELLREF = self::SHEETNAME_PART . '?(?<![:a-z1-9_\.\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])';
21
    const REFHELPER_REGEXP_CELLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)';
22
    const REFHELPER_REGEXP_ROWRANGE = self::SHEETNAME_PART . '?(\$?\d+):(\$?\d+)';
23
    const REFHELPER_REGEXP_COLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
24
25
    /**
26
     * Instance of this class.
27
     *
28
     * @var ?ReferenceHelper
29
     */
30
    private static ?ReferenceHelper $instance = null;
31
32
    private ?CellReferenceHelper $cellReferenceHelper = null;
33
34
    /**
35
     * Get an instance of this class.
36
     */
37 10170
    public static function getInstance(): self
38
    {
39 10170
        if (self::$instance === null) {
40 274
            self::$instance = new self();
41
        }
42
43 10170
        return self::$instance;
44
    }
45
46
    /**
47
     * Create a new ReferenceHelper.
48
     */
49 274
    protected function __construct()
50
    {
51 274
    }
52
53
    /**
54
     * Compare two column addresses
55
     * Intended for use as a Callback function for sorting column addresses by column.
56
     *
57
     * @param string $a First column to test (e.g. 'AA')
58
     * @param string $b Second column to test (e.g. 'Z')
59
     */
60 1
    public static function columnSort(string $a, string $b): int
61
    {
62 1
        return strcasecmp(strlen($a) . $a, strlen($b) . $b);
63
    }
64
65
    /**
66
     * Compare two column addresses
67
     * Intended for use as a Callback function for reverse sorting column addresses by column.
68
     *
69
     * @param string $a First column to test (e.g. 'AA')
70
     * @param string $b Second column to test (e.g. 'Z')
71
     */
72 1
    public static function columnReverseSort(string $a, string $b): int
73
    {
74 1
        return -strcasecmp(strlen($a) . $a, strlen($b) . $b);
75
    }
76
77
    /**
78
     * Compare two cell addresses
79
     * Intended for use as a Callback function for sorting cell addresses by column and row.
80
     *
81
     * @param string $a First cell to test (e.g. 'AA1')
82
     * @param string $b Second cell to test (e.g. 'Z1')
83
     */
84 20
    public static function cellSort(string $a, string $b): int
85
    {
86 20
        sscanf($a, '%[A-Z]%d', $ac, $ar);
87
        /** @var int $ar */
88
        /** @var string $ac */
89 20
        sscanf($b, '%[A-Z]%d', $bc, $br);
90
        /** @var int $br */
91
        /** @var string $bc */
92 20
        if ($ar === $br) {
93 1
            return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
94
        }
95
96 20
        return ($ar < $br) ? -1 : 1;
97
    }
98
99
    /**
100
     * Compare two cell addresses
101
     * Intended for use as a Callback function for sorting cell addresses by column and row.
102
     *
103
     * @param string $a First cell to test (e.g. 'AA1')
104
     * @param string $b Second cell to test (e.g. 'Z1')
105
     */
106 23
    public static function cellReverseSort(string $a, string $b): int
107
    {
108 23
        sscanf($a, '%[A-Z]%d', $ac, $ar);
109
        /** @var int $ar */
110
        /** @var string $ac */
111 23
        sscanf($b, '%[A-Z]%d', $bc, $br);
112
        /** @var int $br */
113
        /** @var string $bc */
114 23
        if ($ar === $br) {
115 2
            return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
116
        }
117
118 22
        return ($ar < $br) ? 1 : -1;
119
    }
120
121
    /**
122
     * Update page breaks when inserting/deleting rows/columns.
123
     *
124
     * @param Worksheet $worksheet The worksheet that we're editing
125
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
126
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
127
     */
128 92
    protected function adjustPageBreaks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
129
    {
130 92
        $aBreaks = $worksheet->getBreaks();
131 92
        ($numberOfColumns > 0 || $numberOfRows > 0)
132 56
            ? uksort($aBreaks, [self::class, 'cellReverseSort'])
133 57
            : uksort($aBreaks, [self::class, 'cellSort']);
134
135 92
        foreach ($aBreaks as $cellAddress => $value) {
136
            /** @var CellReferenceHelper */
137 4
            $cellReferenceHelper = $this->cellReferenceHelper;
138 4
            if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) {
139
                //    If we're deleting, then clear any defined breaks that are within the range
140
                //        of rows/columns that we're deleting
141 1
                $worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE);
142
            } else {
143
                //    Otherwise update any affected breaks by inserting a new break at the appropriate point
144
                //        and removing the old affected break
145 4
                $newReference = $this->updateCellReference($cellAddress);
146 4
                if ($cellAddress !== $newReference) {
147 4
                    $worksheet->setBreak($newReference, $value)
148 4
                        ->setBreak($cellAddress, Worksheet::BREAK_NONE);
149
                }
150
            }
151
        }
152
    }
153
154
    /**
155
     * Update cell comments when inserting/deleting rows/columns.
156
     *
157
     * @param Worksheet $worksheet The worksheet that we're editing
158
     */
159 92
    protected function adjustComments(Worksheet $worksheet): void
160
    {
161 92
        $aComments = $worksheet->getComments();
162 92
        $aNewComments = []; // the new array of all comments
163
164 92
        foreach ($aComments as $cellAddress => &$value) {
165
            // Any comments inside a deleted range will be ignored
166
            /** @var CellReferenceHelper */
167 21
            $cellReferenceHelper = $this->cellReferenceHelper;
168 21
            if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) {
169
                // Otherwise build a new array of comments indexed by the adjusted cell reference
170 21
                $newReference = $this->updateCellReference($cellAddress);
171 21
                $aNewComments[$newReference] = $value;
172
            }
173
        }
174
        //    Replace the comments array with the new set of comments
175 92
        $worksheet->setComments($aNewComments);
176
    }
177
178
    /**
179
     * Update hyperlinks when inserting/deleting rows/columns.
180
     *
181
     * @param Worksheet $worksheet The worksheet that we're editing
182
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
183
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
184
     */
185 92
    protected function adjustHyperlinks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
186
    {
187 92
        $aHyperlinkCollection = $worksheet->getHyperlinkCollection();
188 92
        ($numberOfColumns > 0 || $numberOfRows > 0)
189 56
            ? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort'])
190 57
            : uksort($aHyperlinkCollection, [self::class, 'cellSort']);
191
192 92
        foreach ($aHyperlinkCollection as $cellAddress => $value) {
193 20
            $newReference = $this->updateCellReference($cellAddress);
194
            /** @var CellReferenceHelper */
195 20
            $cellReferenceHelper = $this->cellReferenceHelper;
196 20
            if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) {
197
                $worksheet->setHyperlink($cellAddress, null);
198 20
            } elseif ($cellAddress !== $newReference) {
199 20
                $worksheet->setHyperlink($cellAddress, null);
200 20
                if ($newReference) {
201 20
                    $worksheet->setHyperlink($newReference, $value);
202
                }
203
            }
204
        }
205
    }
206
207
    /**
208
     * Update conditional formatting styles when inserting/deleting rows/columns.
209
     *
210
     * @param Worksheet $worksheet The worksheet that we're editing
211
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
212
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
213
     */
214 92
    protected function adjustConditionalFormatting(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
215
    {
216 92
        $aStyles = $worksheet->getConditionalStylesCollection();
217 92
        ($numberOfColumns > 0 || $numberOfRows > 0)
218 56
            ? uksort($aStyles, [self::class, 'cellReverseSort'])
219 57
            : uksort($aStyles, [self::class, 'cellSort']);
220
221 92
        foreach ($aStyles as $cellAddress => $cfRules) {
222 4
            $worksheet->removeConditionalStyles($cellAddress);
223 4
            $newReference = $this->updateCellReference($cellAddress);
224
225 4
            foreach ($cfRules as &$cfRule) {
226
                /** @var Conditional $cfRule */
227 4
                $conditions = $cfRule->getConditions();
228 4
                foreach ($conditions as &$condition) {
229 4
                    if (is_string($condition)) {
230
                        /** @var CellReferenceHelper */
231 4
                        $cellReferenceHelper = $this->cellReferenceHelper;
232 4
                        $condition = $this->updateFormulaReferences(
233 4
                            $condition,
234 4
                            $cellReferenceHelper->beforeCellAddress(),
235 4
                            $numberOfColumns,
236 4
                            $numberOfRows,
237 4
                            $worksheet->getTitle(),
238 4
                            true
239 4
                        );
240
                    }
241
                }
242 4
                $cfRule->setConditions($conditions);
243
            }
244 4
            $worksheet->setConditionalStyles($newReference, $cfRules);
245
        }
246
    }
247
248
    /**
249
     * Update data validations when inserting/deleting rows/columns.
250
     *
251
     * @param Worksheet $worksheet The worksheet that we're editing
252
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
253
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
254
     */
255 92
    protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
256
    {
257 92
        $aDataValidationCollection = $worksheet->getDataValidationCollection();
258 92
        ($numberOfColumns > 0 || $numberOfRows > 0)
259 56
            ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort'])
260 57
            : uksort($aDataValidationCollection, [self::class, 'cellSort']);
261
262 92
        foreach ($aDataValidationCollection as $cellAddress => $dataValidation) {
263 4
            $newReference = $this->updateCellReference($cellAddress);
264 4
            if ($cellAddress !== $newReference) {
265 4
                $dataValidation->setSqref($newReference);
266 4
                $worksheet->setDataValidation($cellAddress, null);
267 4
                if ($newReference) {
268 4
                    $worksheet->setDataValidation($newReference, $dataValidation);
269
                }
270
            }
271
        }
272
    }
273
274
    /**
275
     * Update merged cells when inserting/deleting rows/columns.
276
     *
277
     * @param Worksheet $worksheet The worksheet that we're editing
278
     */
279 92
    protected function adjustMergeCells(Worksheet $worksheet): void
280
    {
281 92
        $aMergeCells = $worksheet->getMergeCells();
282 92
        $aNewMergeCells = []; // the new array of all merge cells
283 92
        foreach ($aMergeCells as $cellAddress => &$value) {
284 21
            $newReference = $this->updateCellReference($cellAddress);
285 21
            if ($newReference) {
286 21
                $aNewMergeCells[$newReference] = $newReference;
287
            }
288
        }
289 92
        $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
290
    }
291
292
    /**
293
     * Update protected cells when inserting/deleting rows/columns.
294
     *
295
     * @param Worksheet $worksheet The worksheet that we're editing
296
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
297
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
298
     */
299 92
    protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
300
    {
301 92
        $aProtectedCells = $worksheet->getProtectedCells();
302 92
        ($numberOfColumns > 0 || $numberOfRows > 0)
303 56
            ? uksort($aProtectedCells, [self::class, 'cellReverseSort'])
304 57
            : uksort($aProtectedCells, [self::class, 'cellSort']);
305 92
        foreach ($aProtectedCells as $cellAddress => $value) {
306 17
            $newReference = $this->updateCellReference($cellAddress);
307 17
            if ($cellAddress !== $newReference) {
308 17
                $worksheet->unprotectCells($cellAddress);
309 17
                if ($newReference) {
310 17
                    $worksheet->protectCells($newReference, $value, true);
311
                }
312
            }
313
        }
314
    }
315
316
    /**
317
     * Update column dimensions when inserting/deleting rows/columns.
318
     *
319
     * @param Worksheet $worksheet The worksheet that we're editing
320
     */
321 92
    protected function adjustColumnDimensions(Worksheet $worksheet): void
322
    {
323 92
        $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
324 92
        if (!empty($aColumnDimensions)) {
325 25
            foreach ($aColumnDimensions as $objColumnDimension) {
326 25
                $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1');
327 25
                [$newReference] = Coordinate::coordinateFromString($newReference);
328 25
                if ($objColumnDimension->getColumnIndex() !== $newReference) {
329 19
                    $objColumnDimension->setColumnIndex($newReference);
330
                }
331
            }
332
333 25
            $worksheet->refreshColumnDimensions();
334
        }
335
    }
336
337
    /**
338
     * Update row dimensions when inserting/deleting rows/columns.
339
     *
340
     * @param Worksheet $worksheet The worksheet that we're editing
341
     * @param int $beforeRow Number of the row we're inserting/deleting before
342
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
343
     */
344 92
    protected function adjustRowDimensions(Worksheet $worksheet, int $beforeRow, int $numberOfRows): void
345
    {
346 92
        $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true);
347 92
        if (!empty($aRowDimensions)) {
348 7
            foreach ($aRowDimensions as $objRowDimension) {
349 7
                $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex());
350 7
                [, $newReference] = Coordinate::coordinateFromString($newReference);
351 7
                $newRoweference = (int) $newReference;
352 7
                if ($objRowDimension->getRowIndex() !== $newRoweference) {
353 7
                    $objRowDimension->setRowIndex($newRoweference);
354
                }
355
            }
356
357 7
            $worksheet->refreshRowDimensions();
358
359 7
            $copyDimension = $worksheet->getRowDimension($beforeRow - 1);
360 7
            for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) {
361 5
                $newDimension = $worksheet->getRowDimension($i);
362 5
                $newDimension->setRowHeight($copyDimension->getRowHeight());
363 5
                $newDimension->setVisible($copyDimension->getVisible());
364 5
                $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
365 5
                $newDimension->setCollapsed($copyDimension->getCollapsed());
366
            }
367
        }
368
    }
369
370
    /**
371
     * Insert a new column or row, updating all possible related data.
372
     *
373
     * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1')
374
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
375
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
376
     * @param Worksheet $worksheet The worksheet that we're editing
377
     */
378 92
    public function insertNewBefore(
379
        string $beforeCellAddress,
380
        int $numberOfColumns,
381
        int $numberOfRows,
382
        Worksheet $worksheet
383
    ): void {
384 92
        $remove = ($numberOfColumns < 0 || $numberOfRows < 0);
385
386
        if (
387 92
            $this->cellReferenceHelper === null
388 92
            || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
389
        ) {
390 80
            $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
391
        }
392
393
        // Get coordinate of $beforeCellAddress
394 92
        [$beforeColumn, $beforeRow, $beforeColumnString] = Coordinate::indexesFromString($beforeCellAddress);
395
396
        // Clear cells if we are removing columns or rows
397 92
        $highestColumn = $worksheet->getHighestColumn();
398 92
        $highestDataColumn = $worksheet->getHighestDataColumn();
399 92
        $highestRow = $worksheet->getHighestRow();
400 92
        $highestDataRow = $worksheet->getHighestDataRow();
401
402
        // 1. Clear column strips if we are removing columns
403 92
        if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) {
404 24
            $this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet);
405
        }
406
407
        // 2. Clear row strips if we are removing rows
408 92
        if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) {
409 36
            $this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet);
410
        }
411
412
        // Find missing coordinates. This is important when inserting or deleting column before the last column
413 92
        $startRow = $startCol = 1;
414 92
        $startColString = 'A';
415 92
        if ($numberOfRows === 0) {
416 57
            $startCol = $beforeColumn;
417 57
            $startColString = $beforeColumnString;
418 56
        } elseif ($numberOfColumns === 0) {
419 56
            $startRow = $beforeRow;
420
        }
421 92
        $highColumn = Coordinate::columnIndexFromString($highestDataColumn);
422 92
        for ($row = $startRow; $row <= $highestDataRow; ++$row) {
423 81
            for ($col = $startCol, $colString = $startColString; $col <= $highColumn; ++$col, ++$colString) {
424 75
                $worksheet->getCell("$colString$row"); // create cell if it doesn't exist
425
            }
426
        }
427
428 92
        $allCoordinates = $worksheet->getCoordinates();
429 92
        if ($remove) {
430
            // It's faster to reverse and pop than to use unshift, especially with large cell collections
431 57
            $allCoordinates = array_reverse($allCoordinates);
432
        }
433
434
        // Loop through cells, bottom-up, and change cell coordinate
435 92
        while ($coordinate = array_pop($allCoordinates)) {
436 87
            $cell = $worksheet->getCell($coordinate);
437 87
            $cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
438
439
            // Don't update cells that are being removed
440 87
            if ($numberOfColumns < 0 && $cellIndex >= $beforeColumn + $numberOfColumns && $cellIndex < $beforeColumn) {
441 28
                continue;
442
            }
443
444
            // New coordinate
445 87
            $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows);
446
447
            // Should the cell be updated? Move value and cellXf index from one cell to another.
448 87
            if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
449
                // Update cell styles
450 75
                $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
451
452
                // Insert this cell at its new location
453 75
                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
454
                    // Formula should be adjusted
455 37
                    $worksheet->getCell($newCoordinate)
456 37
                        ->setValue($this->updateFormulaReferences($cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true));
457
                } else {
458
                    // Cell value should not be adjusted
459 75
                    $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType());
460
                }
461
462
                // Clear the original cell
463 75
                $worksheet->getCellCollection()->delete($coordinate);
464
            } else {
465
                /*    We don't need to update styles for rows/columns before our insertion position,
466
                        but we do still need to adjust any formulae in those cells                    */
467 61
                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
468
                    // Formula should be adjusted
469 22
                    $cell->setValue($this->updateFormulaReferences($cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true));
470
                }
471
            }
472
        }
473
474
        // Duplicate styles for the newly inserted cells
475 92
        $highestColumn = $worksheet->getHighestColumn();
476 92
        $highestRow = $worksheet->getHighestRow();
477
478 92
        if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) {
479 23
            $this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns);
480
        }
481
482 92
        if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
483 32
            $this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows);
484
        }
485
486
        // Update worksheet: column dimensions
487 92
        $this->adjustColumnDimensions($worksheet);
488
489
        // Update worksheet: row dimensions
490 92
        $this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows);
491
492
        //    Update worksheet: page breaks
493 92
        $this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows);
494
495
        //    Update worksheet: comments
496 92
        $this->adjustComments($worksheet);
497
498
        // Update worksheet: hyperlinks
499 92
        $this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows);
500
501
        // Update worksheet: conditional formatting styles
502 92
        $this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows);
503
504
        // Update worksheet: data validations
505 92
        $this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows);
506
507
        // Update worksheet: merge cells
508 92
        $this->adjustMergeCells($worksheet);
509
510
        // Update worksheet: protected cells
511 92
        $this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows);
512
513
        // Update worksheet: autofilter
514 92
        $this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns);
515
516
        // Update worksheet: table
517 92
        $this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns);
518
519
        // Update worksheet: freeze pane
520 92
        if ($worksheet->getFreezePane()) {
521 1
            $splitCell = $worksheet->getFreezePane();
522 1
            $topLeftCell = $worksheet->getTopLeftCell() ?? '';
523
524 1
            $splitCell = $this->updateCellReference($splitCell);
525 1
            $topLeftCell = $this->updateCellReference($topLeftCell);
526
527 1
            $worksheet->freezePane($splitCell, $topLeftCell);
528
        }
529
530
        // Page setup
531 92
        if ($worksheet->getPageSetup()->isPrintAreaSet()) {
532 6
            $worksheet->getPageSetup()->setPrintArea(
533 6
                $this->updateCellReference($worksheet->getPageSetup()->getPrintArea())
534 6
            );
535
        }
536
537
        // Update worksheet: drawings
538 92
        $aDrawings = $worksheet->getDrawingCollection();
539 92
        foreach ($aDrawings as $objDrawing) {
540 19
            $newReference = $this->updateCellReference($objDrawing->getCoordinates());
541 19
            if ($objDrawing->getCoordinates() != $newReference) {
542 19
                $objDrawing->setCoordinates($newReference);
543
            }
544 19
            if ($objDrawing->getCoordinates2() !== '') {
545 1
                $newReference = $this->updateCellReference($objDrawing->getCoordinates2());
546 1
                if ($objDrawing->getCoordinates2() != $newReference) {
547 1
                    $objDrawing->setCoordinates2($newReference);
548
                }
549
            }
550
        }
551
552
        // Update workbook: define names
553 92
        if (count($worksheet->getParentOrThrow()->getDefinedNames()) > 0) {
554 7
            $this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
555
        }
556
557
        // Garbage collect
558 92
        $worksheet->garbageCollect();
559
    }
560
561 263
    private static function matchSheetName(?string $match, string $worksheetName): bool
562
    {
563 263
        return $match === null || $match === '' || $match === "'\u{fffc}'" || $match === "'\u{fffb}'" || strcasecmp(trim($match, "'"), $worksheetName) === 0;
564
    }
565
566 270
    private static function sheetnameBeforeCells(string $match, string $worksheetName, string $cells): string
567
    {
568 270
        $toString = ($match > '') ? "$match!" : '';
569
570 270
        return str_replace(["\u{fffc}", "'\u{fffb}'"], $worksheetName, $toString) . $cells;
571
    }
572
573
    /**
574
     * Update references within formulas.
575
     *
576
     * @param string $formula Formula to update
577
     * @param string $beforeCellAddress Insert before this one
578
     * @param int $numberOfColumns Number of columns to insert
579
     * @param int $numberOfRows Number of rows to insert
580
     * @param string $worksheetName Worksheet name/title
581
     *
582
     * @return string Updated formula
583
     */
584 284
    public function updateFormulaReferences(
585
        string $formula = '',
586
        string $beforeCellAddress = 'A1',
587
        int $numberOfColumns = 0,
588
        int $numberOfRows = 0,
589
        string $worksheetName = '',
590
        bool $includeAbsoluteReferences = false,
591
        bool $onlyAbsoluteReferences = false
592
    ): string {
593 284
        $callback = fn (array $matches): string => (strcasecmp(trim($matches[2], "'"), $worksheetName) === 0) ? (($matches[2][0] === "'") ? "'\u{fffc}'!" : "'\u{fffb}'!") : "'\u{fffd}'!";
594
        if (
595 284
            $this->cellReferenceHelper === null
596 284
            || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
597
        ) {
598 228
            $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
599
        }
600
601
        //    Update cell references in the formula
602 284
        $formulaBlocks = explode('"', $formula);
603 284
        $i = false;
604 284
        foreach ($formulaBlocks as &$formulaBlock) {
605
            //    Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
606 284
            $i = $i === false;
607 284
            if ($i) {
608 284
                $adjustCount = 0;
609 284
                $newCellTokens = $cellTokens = [];
610
                //    Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
611 284
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' ';
612 284
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
613 284
                if ($matchCount > 0) {
614 3
                    foreach ($matches as $match) {
615 3
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}");
616 3
                        $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences, true), 2);
617 3
                        $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences, false), 2);
618
619 3
                        if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
620 3
                            if (self::matchSheetName($match[2], $worksheetName)) {
621 3
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4");
622
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
623 3
                                $column = 100000;
624 3
                                $row = 10000000 + (int) trim($match[3], '$');
625 3
                                $cellIndex = "{$column}{$row}";
626
627 3
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
628 3
                                $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
629 3
                                ++$adjustCount;
630
                            }
631
                        }
632
                    }
633
                }
634
                //    Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
635 284
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' ';
636 284
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
637 284
                if ($matchCount > 0) {
638 3
                    foreach ($matches as $match) {
639 3
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}");
640 3
                        $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences, true), 0, -2);
641 3
                        $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences, false), 0, -2);
642
643 3
                        if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
644 3
                            if (self::matchSheetName($match[2], $worksheetName)) {
645 3
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4");
646
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
647 3
                                $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000;
648 3
                                $row = 10000000;
649 3
                                $cellIndex = "{$column}{$row}";
650
651 3
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
652 3
                                $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i';
653 3
                                ++$adjustCount;
654
                            }
655
                        }
656
                    }
657
                }
658
                //    Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
659 284
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, "$formulaBlock") ?? "$formulaBlock") . ' ';
660 284
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
661 284
                if ($matchCount > 0) {
662 44
                    foreach ($matches as $match) {
663 44
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}");
664 44
                        $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences, true);
665 44
                        $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences, false);
666
667 44
                        if ($match[3] . $match[4] !== $modified3 . $modified4) {
668 39
                            if (self::matchSheetName($match[2], $worksheetName)) {
669 37
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4");
670 37
                                [$column, $row] = Coordinate::coordinateFromString($match[3]);
671
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
672 37
                                $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
673 37
                                $row = (int) trim($row, '$') + 10000000;
674 37
                                $cellIndex = "{$column}{$row}";
675
676 37
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
677 37
                                $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
678 37
                                ++$adjustCount;
679
                            }
680
                        }
681
                    }
682
                }
683
                //    Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
684
685 284
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' ';
686 284
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
687
688 284
                if ($matchCount > 0) {
689 250
                    foreach ($matches as $match) {
690 250
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}");
691
692 250
                        $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences, null);
693 250
                        if ($match[3] !== $modified3) {
694 248
                            if (self::matchSheetName($match[2], $worksheetName)) {
695 248
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3");
696 248
                                [$column, $row] = Coordinate::coordinateFromString($match[3]);
697 248
                                $columnAdditionalIndex = $column[0] === '$' ? 1 : 0;
698 248
                                $rowAdditionalIndex = $row[0] === '$' ? 1 : 0;
699
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
700 248
                                $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
701 248
                                $row = (int) trim($row, '$') + 10000000;
702 248
                                $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex;
703
704 248
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
705 248
                                $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i';
706 248
                                ++$adjustCount;
707
                            }
708
                        }
709
                    }
710
                }
711 284
                if ($adjustCount > 0) {
712 263
                    if ($numberOfColumns > 0 || $numberOfRows > 0) {
713 255
                        krsort($cellTokens);
714 255
                        krsort($newCellTokens);
715
                    } else {
716 29
                        ksort($cellTokens);
717 29
                        ksort($newCellTokens);
718
                    }   //  Update cell references in the formula
719 263
                    $formulaBlock = str_replace('\\', '', (string) preg_replace($cellTokens, $newCellTokens, $formulaBlock));
720
                }
721
            }
722
        }
723 284
        unset($formulaBlock);
724
725
        //    Then rebuild the formula string
726 284
        return implode('"', $formulaBlocks);
727
    }
728
729
    /**
730
     * Update all cell references within a formula, irrespective of worksheet.
731
     */
732 124
    public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
733
    {
734 124
        $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
735
736 124
        if ($numberOfColumns !== 0) {
737 116
            $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
738
        }
739
740 124
        if ($numberOfRows !== 0) {
741 101
            $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
742
        }
743
744 124
        return $formula;
745
    }
746
747 124
    private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
748
    {
749 124
        $splitCount = preg_match_all(
750 124
            '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
751 124
            $formula,
752 124
            $splitRanges,
753 124
            PREG_OFFSET_CAPTURE
754 124
        );
755
756 124
        $columnLengths = array_map('strlen', array_column($splitRanges[6], 0));
757 124
        $rowLengths = array_map('strlen', array_column($splitRanges[7], 0));
758 124
        $columnOffsets = array_column($splitRanges[6], 1);
759 124
        $rowOffsets = array_column($splitRanges[7], 1);
760
761 124
        $columns = $splitRanges[6];
762 124
        $rows = $splitRanges[7];
763
764 124
        while ($splitCount > 0) {
765 118
            --$splitCount;
766 118
            $columnLength = $columnLengths[$splitCount];
767 118
            $rowLength = $rowLengths[$splitCount];
768 118
            $columnOffset = $columnOffsets[$splitCount];
769 118
            $rowOffset = $rowOffsets[$splitCount];
770 118
            $column = $columns[$splitCount][0];
771 118
            $row = $rows[$splitCount][0];
772
773 118
            if (!empty($column) && $column[0] !== '$') {
774 23
                $column = ((Coordinate::columnIndexFromString($column) + $numberOfColumns) % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
775 23
                $column = Coordinate::stringFromColumnIndex($column);
776 23
                $rowOffset -= ($columnLength - strlen($column));
777 23
                $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
778
            }
779 118
            if (!empty($row) && $row[0] !== '$') {
780 43
                $row = (((int) $row + $numberOfRows) % AddressRange::MAX_ROW) ?: AddressRange::MAX_ROW;
781 43
                $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
782
            }
783
        }
784
785 124
        return $formula;
786
    }
787
788 116
    private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
789
    {
790 116
        $splitCount = preg_match_all(
791 116
            '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
792 116
            $formula,
793 116
            $splitRanges,
794 116
            PREG_OFFSET_CAPTURE
795 116
        );
796
797 116
        $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0));
798 116
        $fromColumnOffsets = array_column($splitRanges[1], 1);
799 116
        $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0));
800 116
        $toColumnOffsets = array_column($splitRanges[2], 1);
801
802 116
        $fromColumns = $splitRanges[1];
803 116
        $toColumns = $splitRanges[2];
804
805 116
        while ($splitCount > 0) {
806 3
            --$splitCount;
807 3
            $fromColumnLength = $fromColumnLengths[$splitCount];
808 3
            $toColumnLength = $toColumnLengths[$splitCount];
809 3
            $fromColumnOffset = $fromColumnOffsets[$splitCount];
810 3
            $toColumnOffset = $toColumnOffsets[$splitCount];
811 3
            $fromColumn = $fromColumns[$splitCount][0];
812 3
            $toColumn = $toColumns[$splitCount][0];
813
814 3
            if (!empty($fromColumn) && $fromColumn[0] !== '$') {
815 2
                $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
816 2
                $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
817
            }
818 3
            if (!empty($toColumn) && $toColumn[0] !== '$') {
819 2
                $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
820 2
                $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
821
            }
822
        }
823
824 116
        return $formula;
825
    }
826
827 101
    private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
828
    {
829 101
        $splitCount = preg_match_all(
830 101
            '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
831 101
            $formula,
832 101
            $splitRanges,
833 101
            PREG_OFFSET_CAPTURE
834 101
        );
835
836 101
        $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0));
837 101
        $fromRowOffsets = array_column($splitRanges[1], 1);
838 101
        $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0));
839 101
        $toRowOffsets = array_column($splitRanges[2], 1);
840
841 101
        $fromRows = $splitRanges[1];
842 101
        $toRows = $splitRanges[2];
843
844 101
        while ($splitCount > 0) {
845 3
            --$splitCount;
846 3
            $fromRowLength = $fromRowLengths[$splitCount];
847 3
            $toRowLength = $toRowLengths[$splitCount];
848 3
            $fromRowOffset = $fromRowOffsets[$splitCount];
849 3
            $toRowOffset = $toRowOffsets[$splitCount];
850 3
            $fromRow = $fromRows[$splitCount][0];
851 3
            $toRow = $toRows[$splitCount][0];
852
853 3
            if (!empty($fromRow) && $fromRow[0] !== '$') {
854 2
                $fromRow = (int) $fromRow + $numberOfRows;
855 2
                $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
856
            }
857 3
            if (!empty($toRow) && $toRow[0] !== '$') {
858 2
                $toRow = (int) $toRow + $numberOfRows;
859 2
                $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
860
            }
861
        }
862
863 101
        return $formula;
864
    }
865
866
    /**
867
     * Update cell reference.
868
     *
869
     * @param string $cellReference Cell address or range of addresses
870
     *
871
     * @return string Updated cell range
872
     */
873 300
    private function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false, ?bool $topLeft = null)
874
    {
875
        // Is it in another worksheet? Will not have to update anything.
876 300
        if (str_contains($cellReference, '!')) {
877 1
            return $cellReference;
878
        }
879
        // Is it a range or a single cell?
880 300
        if (!Coordinate::coordinateIsRange($cellReference)) {
881
            // Single cell
882
            /** @var CellReferenceHelper */
883 288
            $cellReferenceHelper = $this->cellReferenceHelper;
884
885 288
            return $cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences, $topLeft);
886
        }
887
888
        // Range
889 37
        return $this->updateCellRange($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences);
890
    }
891
892
    /**
893
     * Update named formulae (i.e. containing worksheet references / named ranges).
894
     *
895
     * @param Spreadsheet $spreadsheet Object to update
896
     * @param string $oldName Old name (name to replace)
897
     * @param string $newName New name
898
     */
899 765
    public function updateNamedFormulae(Spreadsheet $spreadsheet, string $oldName = '', string $newName = ''): void
900
    {
901 765
        if ($oldName == '') {
902 1
            return;
903
        }
904
905 765
        foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
906 765
            foreach ($sheet->getCoordinates(false) as $coordinate) {
907 132
                $cell = $sheet->getCell($coordinate);
908 132
                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
909 66
                    $formula = $cell->getValueString();
910 66
                    if (str_contains($formula, $oldName)) {
911 1
                        $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
912 1
                        $formula = str_replace($oldName . '!', $newName . '!', $formula);
913 1
                        $cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
914
                    }
915
                }
916
            }
917
        }
918
    }
919
920 7
    private function updateDefinedNames(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
921
    {
922 7
        foreach ($worksheet->getParentOrThrow()->getDefinedNames() as $definedName) {
923 7
            if ($definedName->isFormula() === false) {
924 7
                $this->updateNamedRange($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
925
            } else {
926 4
                $this->updateNamedFormula($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
927
            }
928
        }
929
    }
930
931 7
    private function updateNamedRange(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
932
    {
933 7
        $cellAddress = $definedName->getValue();
934 7
        $asFormula = ($cellAddress[0] === '=');
935 7
        if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
936
            /**
937
             * If we delete the entire range that is referenced by a Named Range, MS Excel sets the value to #REF!
938
             * PhpSpreadsheet still only does a basic adjustment, so the Named Range will still reference Cells.
939
             * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF!
940
             * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace
941
             *      them with a #REF!
942
             */
943 7
            if ($asFormula === true) {
944 5
                $formula = $this->updateFormulaReferences($cellAddress, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true, true);
945 5
                $definedName->setValue($formula);
946
            } else {
947 2
                $definedName->setValue($this->updateCellReference(ltrim($cellAddress, '='), true));
948
            }
949
        }
950
    }
951
952 4
    private function updateNamedFormula(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
953
    {
954 4
        if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
955
            /**
956
             * If we delete the entire range that is referenced by a Named Formula, MS Excel sets the value to #REF!
957
             * PhpSpreadsheet still only does a basic adjustment, so the Named Formula will still reference Cells.
958
             * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF!
959
             * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace
960
             *      them with a #REF!
961
             */
962 3
            $formula = $definedName->getValue();
963 3
            $formula = $this->updateFormulaReferences($formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true);
964 3
            $definedName->setValue($formula);
965
        }
966
    }
967
968
    /**
969
     * Update cell range.
970
     *
971
     * @param string $cellRange Cell range    (e.g. 'B2:D4', 'B:C' or '2:3')
972
     *
973
     * @return string Updated cell range
974
     */
975 37
    private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string
976
    {
977 37
        if (!Coordinate::coordinateIsRange($cellRange)) {
978
            throw new Exception('Only cell ranges may be passed to this method.');
979
        }
980
981
        // Update range
982 37
        $range = Coordinate::splitRange($cellRange);
983 37
        $ic = count($range);
984 37
        for ($i = 0; $i < $ic; ++$i) {
985 37
            $jc = count($range[$i]);
986 37
            for ($j = 0; $j < $jc; ++$j) {
987
                /** @var CellReferenceHelper */
988 37
                $cellReferenceHelper = $this->cellReferenceHelper;
989 37
                if (ctype_alpha($range[$i][$j])) {
990
                    $range[$i][$j] = Coordinate::coordinateFromString(
991
                        $cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences, $onlyAbsoluteReferences, null)
992
                    )[0];
993 37
                } elseif (ctype_digit($range[$i][$j])) {
994
                    $range[$i][$j] = Coordinate::coordinateFromString(
995
                        $cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences, null)
996
                    )[1];
997
                } else {
998 37
                    $range[$i][$j] = $cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences, null);
999
                }
1000
            }
1001
        }
1002
1003
        // Recreate range string
1004 37
        return Coordinate::buildRange($range);
1005
    }
1006
1007 24
    private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void
1008
    {
1009 24
        $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn + $numberOfColumns);
1010 24
        $endColumnId = Coordinate::stringFromColumnIndex($beforeColumn);
1011
1012 24
        for ($row = 1; $row <= $highestRow - 1; ++$row) {
1013 23
            for ($column = $startColumnId; $column !== $endColumnId; ++$column) {
1014 23
                $coordinate = $column . $row;
1015 23
                $this->clearStripCell($worksheet, $coordinate);
1016
            }
1017
        }
1018
    }
1019
1020 36
    private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void
1021
    {
1022 36
        $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn);
1023 36
        ++$highestColumn;
1024
1025 36
        for ($column = $startColumnId; $column !== $highestColumn; ++$column) {
1026 36
            for ($row = $beforeRow + $numberOfRows; $row <= $beforeRow - 1; ++$row) {
1027 36
                $coordinate = $column . $row;
1028 36
                $this->clearStripCell($worksheet, $coordinate);
1029
            }
1030
        }
1031
    }
1032
1033 42
    private function clearStripCell(Worksheet $worksheet, string $coordinate): void
1034
    {
1035 42
        $worksheet->removeConditionalStyles($coordinate);
1036 42
        $worksheet->setHyperlink($coordinate);
1037 42
        $worksheet->setDataValidation($coordinate);
1038 42
        $worksheet->removeComment($coordinate);
1039
1040 42
        if ($worksheet->cellExists($coordinate)) {
1041 20
            $worksheet->getCell($coordinate)->setValueExplicit(null, DataType::TYPE_NULL);
1042 20
            $worksheet->getCell($coordinate)->setXfIndex(0);
1043
        }
1044
    }
1045
1046 92
    private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void
1047
    {
1048 92
        $autoFilter = $worksheet->getAutoFilter();
1049 92
        $autoFilterRange = $autoFilter->getRange();
1050 92
        if (!empty($autoFilterRange)) {
1051 4
            if ($numberOfColumns !== 0) {
1052 2
                $autoFilterColumns = $autoFilter->getColumns();
1053 2
                if (count($autoFilterColumns) > 0) {
1054 2
                    $column = '';
1055 2
                    $row = 0;
1056 2
                    sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
1057 2
                    $columnIndex = Coordinate::columnIndexFromString((string) $column);
1058 2
                    [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
1059 2
                    if ($columnIndex <= $rangeEnd[0]) {
1060 2
                        if ($numberOfColumns < 0) {
1061 1
                            $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter);
1062
                        }
1063 2
                        $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
1064
1065
                        //    Shuffle columns in autofilter range
1066 2
                        if ($numberOfColumns > 0) {
1067 1
                            $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter);
1068
                        } else {
1069 1
                            $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter);
1070
                        }
1071
                    }
1072
                }
1073
            }
1074
1075 4
            $worksheet->setAutoFilter(
1076 4
                $this->updateCellReference($autoFilterRange)
1077 4
            );
1078
        }
1079
    }
1080
1081 1
    private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void
1082
    {
1083
        // If we're actually deleting any columns that fall within the autofilter range,
1084
        //    then we delete any rules for those columns
1085 1
        $deleteColumn = $columnIndex + $numberOfColumns - 1;
1086 1
        $deleteCount = abs($numberOfColumns);
1087
1088 1
        for ($i = 1; $i <= $deleteCount; ++$i) {
1089 1
            $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1);
1090 1
            if (isset($autoFilterColumns[$columnName])) {
1091 1
                $autoFilter->clearColumn($columnName);
1092
            }
1093 1
            ++$deleteColumn;
1094
        }
1095
    }
1096
1097 1
    private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void
1098
    {
1099 1
        $startColRef = $startCol;
1100 1
        $endColRef = $rangeEnd;
1101 1
        $toColRef = $rangeEnd + $numberOfColumns;
1102
1103
        do {
1104 1
            $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
1105 1
            --$endColRef;
1106 1
            --$toColRef;
1107 1
        } while ($startColRef <= $endColRef);
1108
    }
1109
1110 1
    private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void
1111
    {
1112
        // For delete, we shuffle from beginning to end to avoid overwriting
1113 1
        $startColID = Coordinate::stringFromColumnIndex($startCol);
1114 1
        $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
1115 1
        $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1);
1116
1117
        do {
1118 1
            $autoFilter->shiftColumn($startColID, $toColID);
1119 1
            ++$startColID;
1120 1
            ++$toColID;
1121 1
        } while ($startColID !== $endColID);
1122
    }
1123
1124 92
    private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void
1125
    {
1126 92
        $tableCollection = $worksheet->getTableCollection();
1127
1128 92
        foreach ($tableCollection as $table) {
1129 4
            $tableRange = $table->getRange();
1130 4
            if (!empty($tableRange)) {
1131 4
                if ($numberOfColumns !== 0) {
1132 2
                    $tableColumns = $table->getColumns();
1133 2
                    if (count($tableColumns) > 0) {
1134 2
                        $column = '';
1135 2
                        $row = 0;
1136 2
                        sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
1137 2
                        $columnIndex = Coordinate::columnIndexFromString((string) $column);
1138 2
                        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange);
1139 2
                        if ($columnIndex <= $rangeEnd[0]) {
1140 2
                            if ($numberOfColumns < 0) {
1141 1
                                $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table);
1142
                            }
1143 2
                            $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
1144
1145
                            //    Shuffle columns in table range
1146 2
                            if ($numberOfColumns > 0) {
1147 1
                                $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table);
1148
                            } else {
1149 1
                                $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table);
1150
                            }
1151
                        }
1152
                    }
1153
                }
1154
1155 4
                $table->setRange($this->updateCellReference($tableRange));
1156
            }
1157
        }
1158
    }
1159
1160 1
    private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void
1161
    {
1162
        // If we're actually deleting any columns that fall within the table range,
1163
        //    then we delete any rules for those columns
1164 1
        $deleteColumn = $columnIndex + $numberOfColumns - 1;
1165 1
        $deleteCount = abs($numberOfColumns);
1166
1167 1
        for ($i = 1; $i <= $deleteCount; ++$i) {
1168 1
            $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1);
1169 1
            if (isset($tableColumns[$columnName])) {
1170 1
                $table->clearColumn($columnName);
1171
            }
1172 1
            ++$deleteColumn;
1173
        }
1174
    }
1175
1176 1
    private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void
1177
    {
1178 1
        $startColRef = $startCol;
1179 1
        $endColRef = $rangeEnd;
1180 1
        $toColRef = $rangeEnd + $numberOfColumns;
1181
1182
        do {
1183 1
            $table->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
1184 1
            --$endColRef;
1185 1
            --$toColRef;
1186 1
        } while ($startColRef <= $endColRef);
1187
    }
1188
1189 1
    private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void
1190
    {
1191
        // For delete, we shuffle from beginning to end to avoid overwriting
1192 1
        $startColID = Coordinate::stringFromColumnIndex($startCol);
1193 1
        $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
1194 1
        $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1);
1195
1196
        do {
1197 1
            $table->shiftColumn($startColID, $toColID);
1198 1
            ++$startColID;
1199 1
            ++$toColID;
1200 1
        } while ($startColID !== $endColID);
1201
    }
1202
1203 23
    private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void
1204
    {
1205 23
        $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1);
1206 23
        for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
1207
            // Style
1208 22
            $coordinate = $beforeColumnName . $i;
1209 22
            if ($worksheet->cellExists($coordinate)) {
1210 18
                $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
1211 18
                for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
1212 18
                    if (!empty($xfIndex) || $worksheet->cellExists([$j, $i])) {
1213 18
                        $worksheet->getCell([$j, $i])->setXfIndex($xfIndex);
1214
                    }
1215
                }
1216
            }
1217
        }
1218
    }
1219
1220 32
    private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void
1221
    {
1222 32
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
1223 32
        for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) {
1224
            // Style
1225 32
            $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
1226 32
            if ($worksheet->cellExists($coordinate)) {
1227 30
                $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
1228 30
                for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
1229 30
                    if (!empty($xfIndex) || $worksheet->cellExists([$j, $i])) {
1230 27
                        $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
1231
                    }
1232
                }
1233
            }
1234
        }
1235
    }
1236
1237
    /**
1238
     * __clone implementation. Cloning should not be allowed in a Singleton!
1239
     */
1240 1
    final public function __clone()
1241
    {
1242 1
        throw new Exception('Cloning a Singleton is not allowed!');
1243
    }
1244
}
1245